Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 182 ยท Getting Started

The dotnet CLI, Projects and Tooling

Learn the dotnet CLI commands, how a .csproj file works, what Nullable and ImplicitUsings do, file-based apps, global.json and which editor to pick for C#.

Until now you have run C# in the browser. Real projects live on your computer, and almost everything you do there goes through one command-line tool: dotnet. It creates projects, restores libraries, compiles, runs, tests and publishes. Once you understand the handful of commands and the small XML file that describes a project, any .NET codebase becomes readable.

This lesson explains the tooling. The terminal sessions shown here are read-only: our editor has no dotnet command, so those blocks show what you would see on your own machine. The runnable examples use C# to inspect the very same settings from inside a running program.

The dotnet CLI at a glance

Install the .NET SDK (the runtime plus compiler and tools; see How C# and .NET Work) and check it:

Terminal
dotnet --version        # for example 10.0.402
dotnet --list-sdks      # every installed SDK
dotnet --list-runtimes  # every installed runtime

The commands you will use every day:

Command What it does
dotnet new <template> Creates a project or file from a template (console, classlib, webapi, xunit, sln, gitignore, ...).
dotnet restore Downloads the NuGet packages the project needs. Run automatically by build and run.
dotnet build Compiles the project into bin/.
dotnet run Builds if needed and starts the program.
dotnet test Builds and runs the unit tests.
dotnet publish Produces the files you deploy.
dotnet add package <name> Adds a NuGet package reference to the project file.
dotnet watch Re-runs your program (or reloads your web app) whenever you save a file.
dotnet format Fixes code style according to your rules.

Your first project

A typical first session looks like this (read-only; the exact output varies by version):

Terminal
mkdir hello
cd hello
dotnet new console
dotnet run
TEXT
Hello, World!

dotnet new console creates two files: hello.csproj and Program.cs. The program is the top-level-statement file you already know from Program Structure:

C#
// Program.cs (read-only)
Console.WriteLine("Hello, World!");

The folder name becomes the project and assembly name. Running dotnet build adds two new folders: obj/ (intermediate files and the restore result) and bin/ (the compiled output, for example bin/Debug/net10.0/hello.dll). Do not commit those two folders to Git; the template dotnet new gitignore produces a good ignore file.

Anatomy of a .csproj file

The project file is plain XML. This is what a modern console project contains:

XML
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

That is the whole file; the SDK supplies everything else. Let us read it line by line.

  • Sdk="Microsoft.NET.Sdk" pulls in the standard build rules. It automatically includes every *.cs file in the folder and its subfolders, so you never list source files by hand. Web projects use Microsoft.NET.Sdk.Web instead, which also references the ASP.NET Core framework.
  • OutputType is Exe for programs you can start and Library (the default) for code that other projects use.
  • TargetFramework names the .NET version the code is built for. The short name net10.0 means .NET 10. A library might use net8.0;net10.0 (plural TargetFrameworks) to support both.
  • ImplicitUsings makes the compiler add a hidden file of global using directives. For a console project: System, System.Collections.Generic, System.IO, System.Linq, System.Net.Http, System.Threading and System.Threading.Tasks.
  • Nullable turns on nullable reference type analysis, so string means "never null" and string? means "may be null". See Nullable Reference Types.

The language version is not in the file because it follows the target framework: net10.0 uses C# 14. You can override it with <LangVersion>, but that is rarely a good idea.

Other properties you will meet often:

XML
<PropertyGroup>
  <TreatWarningsAsErrors>true</TreatWarningsAsErrors>  <!-- warnings fail the build -->
  <AllowUnsafeBlocks>true</AllowUnsafeBlocks>          <!-- permit unsafe code -->
  <RootNamespace>Shop.Orders</RootNamespace>
  <InvariantGlobalization>true</InvariantGlobalization> <!-- smaller, culture-independent -->
  <PublishAot>true</PublishAot>                         <!-- native ahead-of-time build -->
</PropertyGroup>

<ItemGroup>
  <PackageReference Include="Humanizer.Core" Version="2.14.1" />
  <ProjectReference Include="..\Shop.Core\Shop.Core.csproj" />
</ItemGroup>

PackageReference adds a NuGet library; ProjectReference depends on another project in the same solution. dotnet add package and dotnet add reference edit these lines for you.

Seeing the settings from inside a program

You can ask the running program which runtime it is on and what the compiler enabled. This TryIt prints details of the environment it is running in right now.

C# Which runtime am I running on?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first line comes from the runtime, not from the project file: the project's TargetFramework only decides what you compile against. Command-line arguments are what you pass after dotnet run --, for example dotnet run -- hello 42; in top-level statements they are available as a variable named args.

Implicit usings in action

Because ImplicitUsings is on in our editor, you can use List<T>, File, Task or LINQ without writing any using line. Turn the setting off in a real project and you must write them yourself.

C# No using directives needed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you ever see error CS0246: The type or namespace name 'List<>' could not be found in an old project, a missing using or a disabled ImplicitUsings is the first thing to check.

The Nullable setting in action

The Nullable property changes what the compiler tells you. It never changes how the program runs: nullable annotations are erased at runtime. This example shows the setting that is active in the editor by running code that would draw a warning.

C# Nullable annotations are compile-time only

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both string and string? are the same runtime type; the ? is a hint for the compiler and for people. That is why a project can turn on <Nullable>enable</Nullable> and <TreatWarningsAsErrors> together to turn null mistakes into build failures.

File-based apps

Since .NET 10 you can run a single .cs file without any project file, which is perfect for scripts and experiments:

Terminal
dotnet run hello.cs

The SDK creates a hidden project behind the scenes. Special lines at the top of the file, starting with #:, configure it:

C#
#:property LangVersion=preview
#:package Humanizer.Core@2.14.1

using Humanizer;

Console.WriteLine("hello world".Humanize());

You can even make the file executable on Linux and macOS with a #!/usr/bin/env dotnet line. When the script outgrows one file, dotnet project convert hello.cs turns it into a regular project folder. The code in our editor behaves like such a single file, with no packages.

Solutions and several projects

Real applications have several projects: a web API, a class library with the business logic, a test project. A solution file groups them so that one command builds everything.

Terminal
dotnet new sln -n Shop
dotnet new classlib -o src/Shop.Core
dotnet new webapi   -o src/Shop.Api
dotnet new xunit    -o tests/Shop.Tests
dotnet sln add src/Shop.Core src/Shop.Api tests/Shop.Tests
dotnet add src/Shop.Api reference src/Shop.Core
dotnet add tests/Shop.Tests reference src/Shop.Core
dotnet test

New projects use the modern .slnx solution format, which is a short XML file listing the projects. Building at the solution level compiles each project in the right order, because MSBuild (the build engine behind dotnet build) follows the ProjectReference lines.

global.json and shared settings

Different machines may have different SDKs installed. A global.json file next to your solution pins the version used for the folder, so everyone (and your build server) uses the same compiler:

JSON
{
  "sdk": {
    "version": "10.0.402",
    "rollForward": "latestFeature"
  }
}

rollForward says how flexible the pin is; latestFeature accepts newer feature bands of the same major version. For settings that every project in a repository should share, put a Directory.Build.props file in the root. MSBuild merges it into every project below it automatically:

XML
<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <LangVersion>latest</LangVersion>
  </PropertyGroup>
</Project>

An .editorconfig file in the root controls code style (indentation, naming rules, brace placement) and is understood by every editor and by dotnet format.

Debug and Release

dotnet build uses the Debug configuration by default: no optimizations, extra symbols, easy stepping in a debugger. dotnet build -c Release (or dotnet publish) turns the optimizer on. Always measure performance in Release; Debug code can be several times slower. Timings taken in our editor prove little (see Measuring and Improving Performance).

Code can even depend on the configuration. The DEBUG symbol is defined in Debug builds, and [Conditional] methods disappear completely from builds where the symbol is missing. Run this and see which branch our editor takes.

C# Compile-time symbols

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In a real project the SDK defines DEBUG for Debug builds, and also symbols such as NET10_0_OR_GREATER derived from the target framework (not defined in our single-file editor). That is how libraries support several .NET versions in one code base.

Terminal
dotnet publish -c Release -o out                          # framework-dependent
dotnet publish -c Release -r linux-x64 --self-contained   # includes the runtime

A framework-dependent publish is small but needs the .NET runtime on the target machine. A self-contained publish copies the runtime next to your program, so it runs anywhere. NativeAOT (PublishAot) compiles to a native executable with fast start-up but some limits on reflection.

Choosing an editor

C# works with several excellent tools, and the project file is the same in all of them:

  • Visual Studio (Windows) is the full-featured IDE with the best debugger and designers.
  • Visual Studio Code with the C# Dev Kit extension is lightweight, runs everywhere and is free.
  • JetBrains Rider is a cross-platform IDE with strong refactoring tools; it is free for non-commercial use.
  • Any text editor plus the terminal works; the compiler does not care.

Useful features in all of them: IntelliSense (completion), quick fixes for compiler errors, rename refactoring, the debugger with breakpoints and watch windows, and a test explorer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which command compiles and starts a console project?

    dotnet run builds the project if necessary and then starts it. dotnet new only creates files and restore only downloads packages.
  2. 2. What does <TargetFramework>net10.0</TargetFramework> decide?

    The target framework chooses the .NET APIs you compile against, and the default language version follows it (C# 14 for net10.0).
  3. 3. What does ImplicitUsings enable do?

    The SDK generates a file of global usings for a short list of common namespaces. Nullable analysis is the separate Nullable property.
  4. 4. Where should you put settings that all projects in a repository share?

    MSBuild automatically imports Directory.Build.props for all projects below it, so shared properties live in one place.
  5. 5. What is global.json for?

    global.json selects the SDK version (with a roll-forward policy) so every machine and build server uses the same tools.

Summary

  • The dotnet CLI creates (new), builds, runs, tests and publishes projects; restore happens automatically.
  • A .csproj is a small XML file: the SDK, OutputType, TargetFramework, ImplicitUsings and Nullable are the settings you will see most.
  • Source files are included automatically; packages and other projects are added with PackageReference and ProjectReference.
  • ImplicitUsings supplies common using directives; Nullable turns on compile-time null analysis that does not change runtime behavior.
  • .NET 10 can run a single file with dotnet run file.cs, configured with #: lines.
  • Use solutions to group projects, global.json to pin the SDK, Directory.Build.props and .editorconfig for shared settings.
  • Measure and publish in the Release configuration; choose framework-dependent, self-contained or NativeAOT publishing to suit the target machine.

Next: Variables and var