.NET Core  

Run C# File Instantly with .NET 10

Introduction

Microsoft has introduced a groundbreaking feature in .NET 10 Preview 4, the ability to run C# files directly using dotnet run app.cs. This enhancement streamlines the development process, making it more accessible for beginners, educators, and professionals who want to quickly test or prototype code without the overhead of creating a full project.

Prerequisites

  • Install .NET 10 Preview 4 or later
  • Confirm your version by running: dotnet-- version

What is dotnet run app.cs?

Running a C# program traditionally required setting up a project with a .csproj file. With the new dotnet run app.cs command, you can execute a standalone .cs file directly, similar to scripting languages like Python or JavaScript. This lowers the entry barrier and speeds up experimentation and learning.

A Simple Example

Create a C# File

Create a file named helloworld.cs with the following content

Console.WriteLine("Hello, World!");

Run the File

dotnet run helloworld.cs

Output

Hello, World!

Enhancing File-Based Apps with Directives

.NET 10 introduces file-level directives that allow you to specify configurations directly within your .cs file.

Referencing NuGet Packages

#:package [email protected]

using Newtonsoft.Json;

var person = new { Name = "Alice", Age = 30 };
string json = JsonConvert.SerializeObject(person);

Console.WriteLine(json);

This code uses Newtonsoft.Json to serialize an object to JSON.

Specifying an SDK

#:sdk Microsoft.NET.Sdk.Web

This directive specifies the SDK to use when running the script.

Transitioning to a Full Project

As your application grows, you might want to convert your single-file script into a full-fledged project:

dotnet project convert helloworld.cs

This command generates the necessary project files to scale your app further.

Benefits of dotnet run app.cs

  • Simplicity: No need for a project structure
  • Speed: Quickly test or demo code
  • Flexibility: Easily add NuGet packages and SDKs
  • Scalability: Seamlessly transition to a full project

Conclusion

The dotnet run app.cs feature in .NET 10 brings scripting convenience to the C# ecosystem. Whether you're a student, teacher, or experienced developer, this makes testing and prototyping faster and easier than ever before.

References

Official Blog: https://devblogs.microsoft.com/dotnet/announcing-dotnet-run-app/
.NET 10 SDK Download: https://dotnet.microsoft.com/en-us/download/dotnet/10.0

Thank You, and Stay Tuned for More!

More Articles from my Account