.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@Versionfor NuGet references,#:property Name=Valuefor MSBuild properties,#:sdkto choose the SDK and#:projectfor 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=falsefor 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.