dotnet run in .NET 10: Single-File C# Is Finally Here

Fellow code crafters, .NET 10 brings a nifty upgrade to the `dotnet run` command that's a game-changer for quick prototyping and scripting. Forget the tedious project scaffolding for simple tasks! Now...

dotnet run in .NET 10: Single-File C# Is Finally Here

Fellow code crafters, .NET 10 brings a nifty upgrade to the `dotnet run` command that's a game-changer for quick prototyping and scripting. Forget the tedious project scaffolding for simple tasks! Now, you can directly execute a single `.cs` file with `dotnet run app.cs`, much like you would with Python or Node.js. This means less friction and more focus on the code itself. It's all thanks to the introduction of top-level statements in C# 9, which eliminates the need for boilerplate code. No more `namespace MyApp`, `class Program`, or `static void Main`. Just pure, executable C#.

The real power lies in the directives. Need a NuGet package? Just add `#:package Humanizer@2.14.1` at the top of your file – no `dotnet add package` required. Building a mini web API? Set the SDK with `#:sdk Microsoft.NET.Sdk.Web` and you are good to go. Think of these directives as a lightweight `.csproj` replacement for simple scenarios. You can even set build properties like `#:property LangVersion preview`. And for you Unix folks, you can use a shebang (`#!/usr/bin/env dotnet run`) to execute your C# file as a script. When your script is ready to graduate to a full-fledged project, `dotnet project convert app.cs` will handle the migration, transforming your directives into proper MSBuild properties.

While `dotnet run app.cs` isn't meant for production (use `dotnet publish` instead!), it's perfect for data exploration, API testing, and one-off automation tasks. It's also worth noting that this feature requires .NET 10 and is currently limited to single-file execution. However, the ability to quickly test ideas and automate tasks with the full power of C# is a welcome addition to our toolbox. Happy coding!


📰 Original article: https://dev.to/mashrulhaque/dotnet-run-in-net-10-single-file-c-is-finally-here-1gdi

This content has been curated and summarized for Code Crafts readers.