Skip to content

File-based app directives C# 14.0new scenarios

New preprocessor directives for configuring file-based apps.

.NET 10 introduces a file-based app model where a single .cs file can be a complete application without a project file. C# 14 adds new #: preprocessor directives to configure these apps directly within the source file: package references, MSBuild properties, the SDK and project references.

Code ​

csharp
#:package [email protected]
#:property PublishAot=false

using Newtonsoft.Json;

var obj = new { Name = "Hello", Value = 42 };
Console.WriteLine(JsonConvert.SerializeObject(obj));
csharp
// Required a .csproj file alongside your code:
//
// <Project Sdk="Microsoft.NET.Sdk">
//   <PropertyGroup>
//     <OutputType>Exe</OutputType>
//     <TargetFramework>net10.0</TargetFramework>
//     <ImplicitUsings>enable</ImplicitUsings>
//     <Nullable>enable</Nullable>
//   </PropertyGroup>
//   <ItemGroup>
//     <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
//   </ItemGroup>
// </Project>

using Newtonsoft.Json;

var obj = new { Name = "Hello", Value = 42 };
Console.WriteLine(JsonConvert.SerializeObject(obj));

Notes ​

  • Directives use the #: prefix to distinguish them from existing # preprocessor directives
  • Used by file-based apps (single-file programs run with dotnet run file.cs); the compiler ignores them and a project-based build warns about them
  • Supports #:package Name@Version for NuGet references, #:property Name=Value for MSBuild properties, #:sdk to choose the SDK and #:project for project references
  • A #! shebang line on the first line lets Unix systems run the file directly
  • File-based apps enable implicit usings, nullable reference types and Native AOT publishing by default, hence PublishAot=false for a reflection-heavy package like Newtonsoft.Json
  • See Top-level statements C# 9.0 for the single-file program that the directives add package and SDK references to.

More information ​

Powered by Intracia