C# cheat sheet

A scannable C# reference: 10 short snippets across 7 topics, each linking back to the lesson it came from.

At a glance

TopicWhat it covers
Syntax and typesC# compiles to an assembly that runs on the .NET runtime. The build is driven by a .csproj file, so the unit of work islesson
LINQ and async/awaitLINQ is a set of extension methods over IEnumerable<T>, and over IQueryable<T> when a provider such as EFlesson
Setting up .NET: SDK, CLI and project layoutThe .NET SDK contains the runtime, the compilers and the CLI. One installation can build and run for several targetlesson
File I/O, streams and JSON serializationRead and write files asynchronously, stream instead of buffering, and serialise JSON fast with source generation andlesson
Dependency injection and configurationA singleton that captures a scoped service is the classic captive dependency: the scoped instance never gets releasedlesson
Data access with Entity Framework CoreAlways read the generated migration before applying it. A rename that EF models as a drop and an add silently deletes alesson
Modern C# 12 to 14 features and performanceA primary-constructor parameter is captured into a hidden field only if it is used in a member body. If it is only usedlesson

Quick snippets

Syntax and types

A project, not just a file

dotnet new console -o Hello
cd Hello
dotnet run                       # restore, build and execute
dotnet build -c Release          # compile only
dotnet add package Humanizer     # add a NuGet dependency
dotnet publish -c Release -r linux-x64 --self-contained

Full lesson: Syntax and types →

LINQ and async/await

Deferred execution

var numbers = new List<int> { 1, 2, 3 };

var even = numbers.Where(n => n % 2 == 0);   // nothing has run yet
numbers.Add(4);
var list = even.ToList();                    // runs here: 2 and 4

var query = numbers.Where(n => n > 1);
Console.WriteLine(query.Count());            // executes
Console.WriteLine(query.Count());            // executes again

var snapshot = query.ToList();               // materialise when the source is volatile

Full lesson: LINQ and async/await →

Setting up .NET: SDK, CLI and project layout

The SDK and the command loop

dotnet --version              # the SDK in use
dotnet --list-sdks
dotnet --list-runtimes
dotnet --info                 # everything, including the RID and base path

dotnet new console -o Hello
cd Hello
dotnet run                    # restore, build and run in one step
dotnet build -c Release
dotnet publish -c Release -r linux-x64 --self-contained false -o out
dotnet test
dotnet format                 # apply the standard style and analysers

Solutions, projects and target frameworks

dotnet new sln -n Shop
dotnet new classlib -o Shop.Core
dotnet new web -o Shop.Api
dotnet sln add Shop.Core Shop.Api
dotnet add Shop.Api reference Shop.Core
dotnet add Shop.Api package Microsoft.EntityFrameworkCore.Sqlite

# multi-targeting: one library, two runtimes
# <TargetFrameworks>net8.0;net10.0</TargetFrameworks>

Solutions, projects and target frameworks

<!-- Directory.Build.props — one place for settings shared by every project -->
<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <Deterministic>true</Deterministic>
  </PropertyGroup>
</Project>

Full lesson: Setting up .NET: SDK, CLI and project layout →

File I/O, streams and JSON serialization

System.Text.Json and source generation

// a converter for a type the serialiser cannot guess
public sealed class MoneyConverter : JsonConverter<decimal>
{
    public override decimal Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions o)
        => decimal.Parse(reader.GetString()!, System.Globalization.CultureInfo.InvariantCulture);

    public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions o)
        => writer.WriteStringValue(value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
}

Full lesson: File I/O, streams and JSON serialization →

Dependency injection and configuration

The generic host and service registration

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseDefaultServiceProvider((context, options) =>
{
    options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
    options.ValidateOnBuild = true;      // fail at startup, not on first request
});

Full lesson: Dependency injection and configuration →

Data access with Entity Framework Core

DbContext and entities

dotnet tool install --global dotnet-ef
dotnet ef migrations add InitialSchema
dotnet ef database update
dotnet ef migrations script --idempotent -o migrate.sql   # inspect before applying
dotnet ef migrations remove                                 # undo an unapplied migration

Querying, projections and loading

// bulk operations without loading anything
int changed = await db.Orders
    .Where(o => o.CreatedAt < cutoff)
    .ExecuteUpdateAsync(s => s.SetProperty(o => o.Archived, true), ct);

int removed = await db.Orders
    .Where(o => o.Archived && o.CreatedAt < older)
    .ExecuteDeleteAsync(ct);

Full lesson: Data access with Entity Framework Core →

Modern C# 12 to 14 features and performance

Trimming, AOT and measuring

<!-- publish trim-safe, AOT-friendly output -->
<PropertyGroup>
  <PublishTrimmed>true</PublishTrimmed>
  <TrimMode>full</TrimMode>
  <PublishAot>true</PublishAot>
  <InvariantGlobalization>true</InvariantGlobalization>
  <EnableTrimAnalyzer>true</EnableTrimAnalyzer>
  <EnableAotAnalyzer>true</EnableAotAnalyzer>
  <StackTraceSupport>true</StackTraceSupport>
</PropertyGroup>

Full lesson: Modern C# 12 to 14 features and performance →

FAQ

Is this C# cheat sheet free to use?
Yes. No sign-up and no tracking: the page is static, every example is on the page itself, and you can print it or save it as a one-page reference.
Where do the examples come from?
Every snippet is taken from the 7 lessons of the C# course on this site, and each section links back to the lesson it was pulled from.
How do I go deeper than a cheat sheet?
Open the full C# course — it carries the worked explanations, the edge cases and the exercises behind every line here.

C C++ Scala Lua Dart

Last refreshed 2026-09-27.