The dotnet CLI: The Workbench

The dotnet CLI: The Workbench in C#: An IDE is a showroom. Everything is arranged for you, the buttons are labelled, and pressing the green triangle makes your…

The Analogy: The Workbench Behind the Showroom

An IDE is a showroom. Everything is arranged for you, the buttons are labelled, and pressing the green triangle makes your program run. It is a genuinely good way to work — right up until the moment you need to explain to a build server, which has no screen and no mouse, exactly how to produce the same result.

Behind the showroom there is a workbench, and every tool on it has a name you can say out loud. dotnet build. dotnet test. dotnet publish. The IDE's green triangle is a handle bolted onto one of those tools; the tool itself was always there. Learning the workbench is what makes your build reproducible, because a command you can type is a command a script can type, and a script is the only kind of build instruction that never gets forgotten.

The workbench has one more property that matters: everything on it is a project, described by a file you can read. A .csproj is not a mysterious IDE artefact — it is a short XML document saying which framework to target, which packages to reference, and which other projects this one depends on. The CLI reads it, MSBuild acts on it, and both will tell you exactly what they did if you ask.

This lesson is about the tools you will use every day and the handful you will be very glad to know about the day something breaks. It is also the point where a C# project stops being "a thing my editor runs" and becomes something you can build, test, package and ship from a terminal on a machine you have never logged into.


Syntax or Core Structure

Building a three-project solution from nothing, one command at a time:

dotnet new sln      -n Shop
dotnet new classlib -o src/Shop.Core
dotnet new console  -o src/Shop.Cli
dotnet new xunit    -o tests/Shop.Tests

dotnet sln add src/Shop.Core src/Shop.Cli tests/Shop.Tests
dotnet add src/Shop.Cli   reference src/Shop.Core
dotnet add tests/Shop.Tests reference src/Shop.Core

dotnet build
dotnet test
dotnet run --project src/Shop.Cli

Output: (abridged - the exact wording varies by SDK version)

The template "Solution File" was created successfully.
The template "Class Library" was created successfully.
The template "Console App" was created successfully.
The template "xUnit Test Project" was created successfully.

Project 'src/Shop.Core/Shop.Core.csproj' added to the solution.
Project 'src/Shop.Cli/Shop.Cli.csproj' added to the solution.
Project 'tests/Shop.Tests/Shop.Tests.csproj' added to the solution.
Reference 'src/Shop.Core/Shop.Core.csproj' added to the project.

Build succeeded.
    0 Warning(s)
    0 Error(s)

Passed!  - Failed: 0, Passed: 1, Skipped: 0, Total: 1
Hello, World!

Read that sequence again and notice what is not there: no restore step, and no dependency ordering. dotnet build restores packages implicitly and works out from the project references that Shop.Core must be built before Shop.Cli. dotnet test builds first, then runs the tests. Each command does the minimum work needed to satisfy the one you actually asked for, which is why dotnet run on an unchanged project is fast — everything up the chain was already up to date.

The layout is a convention worth adopting: a solution file at the root, application and library projects under src/, test projects under tests/. Nothing in the tooling requires it, and every .NET developer who opens your repository will immediately know where to look.

The one asymmetry to remember is that dotnet run and dotnet test need to know which project, because a solution can contain many. From the repository root that means --project src/Shop.Cli; from inside the project directory the argument is unnecessary.


Technical Depth: The Tools Worth Knowing

CommandWhat it doesNote
dotnet new <template>Scaffolds from a templatedotnet new list shows all of them
dotnet restoreResolves and downloads packagesImplicit in build/run/test
dotnet buildCompiles to bin/Debug/--no-restore to skip the check
dotnet runBuilds then runs-- separates your args from its own
dotnet watchRebuilds and restarts on file changeHot reload for many edits
dotnet testBuilds and runs test projects--filter, --logger, --collect
dotnet formatFixes whitespace and style--verify-no-changes for CI
dotnet publishProduces a deployable folderThis, not build, is what you ship
dotnet packProduces a .nupkgFor libraries you distribute
dotnet tool installInstalls a CLI tool-g global, or local via a manifest

SDK, runtime, and which one you have

dotnet --info          # everything: SDK, runtimes, RID, install paths
dotnet --list-sdks     # 9.0.100 [C:\Program Files\dotnet\sdk]
dotnet --list-runtimes # Microsoft.NETCore.App 9.0.0 [...]

The SDK builds code; the runtime executes it. A build server needs the SDK, a production container usually only needs the runtime — which is why the standard Docker setup uses two stages, an SDK image to publish and a slim runtime image to run.

Pin the SDK version when a team or a CI pipeline must agree:

{
  "sdk": { "version": "9.0.100", "rollForward": "latestFeature" }
}

A global.json in the repository root applies to every project below it, and rollForward decides how much newer an installed SDK may be before the build refuses.

Build is not publish

dotnet build produces something that runs on this machine, from this folder, with dependency resolution still relying on your NuGet cache. dotnet publish gathers everything the app needs into one output directory — your assemblies, every package assembly, the runtime config, and optionally the runtime itself. Deploying bin/Debug is the classic first-deployment mistake.

dotnet publish -c Release -o out                          # framework-dependent
dotnet publish -c Release -r linux-x64 --self-contained    # ships the runtime too
dotnet publish -c Release -p:PublishSingleFile=true
dotnet publish -c Release -p:PublishTrimmed=true           # smaller, reflection-hostile
dotnet publish -c Release -p:PublishAot=true               # native, fastest start

-c Release is not optional in spirit: a Debug build disables optimisations and emits assertions, and shipping one is both slower and more revealing than you want.

Where the artefacts live

obj/ holds intermediate state — the restore graph, generated files, per-file compilation output — and bin/ holds the result. Both are entirely derived, both belong in .gitignore, and deleting them is a legitimate diagnostic step. dotnet clean does it politely; removing the folders does it thoroughly, and is the fix for a surprising share of "it builds on my machine" mysteries.

Targets and identifiers

<TargetFramework>net9.0</TargetFramework>
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>   <!-- libraries: plural -->
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>

The target framework moniker says which API surface you compile against; the runtime identifier says which OS and CPU you produce output for. Libraries often multi-target so consumers on older frameworks are not left behind; applications target one framework and pick a RID only when publishing self-contained.

When the build misbehaves

dotnet build -v n                      # normal verbosity; d and diag go deeper
dotnet build -bl                       # writes msbuild.binlog for the log viewer
dotnet msbuild -t:Restore,Build
dotnet nuget locals all --clear        # last resort for corrupt package caches

A binary log is the single most effective build-debugging tool in .NET: it records every target, every property and every file, and the MSBuild Structured Log Viewer will tell you exactly which import set that property you cannot account for.

Diagnostics tools

dotnet-counters, dotnet-trace, dotnet-dump and dotnet-gcdump install as global tools and attach to a running process by PID. They are how you get GC counts, allocation traces and heap dumps out of a container without a debugger — and worth installing before you need them, not during the incident.


Real World Example: A Build Script Anyone Can Run

The most valuable file in a .NET repository is often twenty lines of shell. It documents the build, it is identical on a laptop and on a build agent, and it fails loudly rather than half-succeeding.

#!/usr/bin/env bash
set -euo pipefail                 # stop on the first error, not the last

CONFIG="${1:-Release}"
OUT="artifacts"

echo "== SDK =="
dotnet --version

echo "== restore =="
dotnet restore Shop.sln

echo "== format check =="
dotnet format Shop.sln --verify-no-changes --verbosity minimal

echo "== build =="
dotnet build Shop.sln -c "$CONFIG" --no-restore /warnaserror

echo "== test =="
dotnet test Shop.sln -c "$CONFIG" --no-build \
  --logger "trx;LogFileName=results.trx" \
  --collect:"XPlat Code Coverage"

echo "== publish =="
rm -rf "$OUT"
dotnet publish src/Shop.Cli -c "$CONFIG" --no-build -o "$OUT"

echo "== done: $(ls "$OUT" | wc -l) files in $OUT =="

Output: (abridged)

== SDK ==
9.0.100
== restore ==
  Determining projects to restore...
  Restored /repo/src/Shop.Core/Shop.Core.csproj (in 412 ms).
== format check ==
== build ==
  Shop.Core -> /repo/src/Shop.Core/bin/Release/net9.0/Shop.Core.dll
  Shop.Cli -> /repo/src/Shop.Cli/bin/Release/net9.0/Shop.Cli.dll
  Build succeeded.
== test ==
Passed!  - Failed: 0, Passed: 12, Skipped: 0, Total: 12
== publish ==
  Shop.Cli -> /repo/artifacts/
== done: 7 files in artifacts ==

The set -euo pipefail line is the most important one in the file. Without -e, a failing dotnet test prints its errors and the script cheerfully carries on to publish a broken build; with it, the first non-zero exit stops everything. -u catches a misspelled variable instead of substituting an empty string, and pipefail makes a failure anywhere in a pipeline count. These four letters are the difference between a script and a suggestion.

The --no-restore and --no-build flags encode the pipeline's structure. Restore happens once, build happens once, and test and publish reuse that output instead of quietly rebuilding — which is faster, and more importantly means the artefact you publish is byte-for-byte the one the tests ran against. Drop those flags and dotnet publish may rebuild with different inputs, which is exactly the kind of gap that produces a release nobody can reproduce.

Two flags turn advisory checks into gates. dotnet format --verify-no-changes exits non-zero if anything is misformatted rather than fixing it silently, so style is enforced by the build instead of by review comments. /warnaserror promotes every compiler warning to an error, which is only tolerable if you adopt it early — on an old codebase, start with -warnaserror:CS0168,CS8600 and expand the list over time.

Note also CONFIG="${1:-Release}": the script defaults to Release, so the safe thing happens when someone runs it with no arguments, while ./build.sh Debug is still available for local diagnosis. Defaults that favour the correct behaviour are worth more than documentation about which flag to pass.


Common Mistakes

  1. Deploying bin/Release instead of dotnet publish output. build output relies on your local package cache; publish gathers everything the app actually needs.
  2. Shipping a Debug build. Optimisations are off, assertions are on, and stack traces expose more than you intended. Always -c Release for anything leaving your machine.
  3. Committing bin/ and obj/. They are derived output, they conflict on every merge, and they can leak absolute paths. Start from dotnet new gitignore.
  4. Relying on the IDE for the build definition. If the build cannot be reproduced from a terminal, it cannot be reproduced on a build agent either.
  5. Not pinning the SDK. Without a global.json, a teammate on a newer SDK can get different analyser results or a different language version.
  6. Passing arguments to dotnet run without --. dotnet run --verbose is a CLI flag; dotnet run -- --verbose is your program's argument.
  7. Guessing at build failures. Raise the verbosity or capture a binary log with -bl before changing project files at random.
  8. Enabling PublishTrimmed or PublishAot without testing. Both remove code that only reflection can see, and the failure appears at run time in production, not at build time.

Best Practices

  • Keep a build.sh (or build.ps1) at the repository root that restores, formats, builds, tests and publishes, and make CI call that same script.
  • Pin the SDK in global.json and let rollForward control how much drift is acceptable.
  • Use the src/ and tests/ convention with a solution file at the root, so any .NET developer can navigate the repository immediately.
  • Chain --no-restore and --no-build through the pipeline so each stage reuses the previous stage's output.
  • Treat warnings as errors from the first commit; retrofitting the habit onto a large codebase is far harder.
  • Install dotnet-counters, dotnet-trace and dotnet-dump as tools now, and record a local manifest with dotnet new tool-manifest so versions are pinned per repository.
  • Reach for dotnet watch while developing and dotnet format --verify-no-changes in CI.
  • Use two-stage Docker builds: an SDK image to publish, a runtime image to run.

Practice Exercises

  1. Build the three-project solution from the syntax section, add a class in Shop.Core, call it from Shop.Cli, and write one xUnit test for it. Do the whole thing from a terminal without opening an IDE.
  2. Write a build.sh for that solution modelled on the example, then deliberately break a test and confirm the script exits non-zero and never reaches the publish step.
  3. Publish the CLI four ways — framework-dependent, self-contained, single-file, and trimmed — and record the output size of each. Explain the trade-off you would accept for a container deployment.
  4. Add a global.json pinning an SDK version that is not installed, run dotnet build, and read the error. Then set rollForward to latestMajor and explain precisely what changed.