Run C# with the dotnet CLI

C# · Essentials · 10 min

Every C# project, from a script to a web service, is created, built, tested and published through the same dotnet CLI.

C# code is compiled to IL (intermediate language) and run by the .NET runtime, which JIT-compiles it to machine code. You install the .NET SDK, which gives you the dotnet command.

  • dotnet new console -o Hello creates a folder with Hello.csproj (the project file) and Program.cs.
  • dotnet run builds and runs the project; dotnet build only compiles into bin/.
  • dotnet test, dotnet add package <name> and dotnet publish cover testing, NuGet packages and deployment.

Since C# 9, a program can use top-level statements: you write code directly in Program.cs without a class Program and static void Main. The compiler generates the entry point for you, and args is available as a string[]. Only one file in a project may contain top-level statements.

.NET 10 adds file-based apps: dotnet run app.cs runs a single .cs file with no project at all, which is handy for scripts and experiments.

Console.WriteLine prints a line, Console.ReadLine reads one (it returns null at end of input, hence string?). The $"..." syntax is an interpolated string, covered in the strings lesson.

The project file sets the TargetFramework (for example net10.0) and options such as <Nullable>enable</Nullable> and <ImplicitUsings>enable</ImplicitUsings>, which pre-imports common namespaces like System and System.Linq.

Example

// Program.cs (create with: dotnet new console -o Hello; then: dotnet run)
// Top-level statements: no class or Main method needed.
Console.WriteLine("Hello, World!");        // Hello, World!
Console.WriteLine($"Args: {args.Length}");  // Args: 0

Console.Write("Your name? ");
string? name = Console.ReadLine();         // null if stdin is closed
Console.WriteLine($"Hi, {name ?? "stranger"}!");

Remember

  • The .NET SDK's dotnet CLI creates, builds, runs, tests and publishes projects
  • Top-level statements replace the Main method boilerplate
  • The .csproj file holds the target framework and compiler options

Watch out for

  • Putting top-level statements in two files of the same project: only one entry point is allowed.

Check yourself

  1. What does dotnet run do in a project folder?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/dotnet/core/tools/

Builds on

Nothing: this is a foundation.

Unlocks