Quick start

Introduction

C# is a statically typed language for .NET. This reference covers syntax, types, nullables, collections, LINQ, async, records, patterns, generics and the CLI.

Create a project

dotnet new console -o hello
cd hello
dotnet run

new scaffolds a project, run compiles and runs it.

See: dotnet new

Run one file

dotnet run hello.cs

A single .cs file runs without a project file.

See: File-based apps

Build and publish

dotnet build -c Release
dotnet publish -c Release -o out
dotnet out/hello.dll

build compiles, publish writes the runnable output to out/.

See: dotnet publish

Syntax

Program structure

using System.Text;

Console.WriteLine("Hello");

var sb = new StringBuilder();

Statements at the top of the file become Main.

See: Top-level statements

Namespaces

namespace Shop.Orders;

public class Order
{
    public int Id { get; set; }
}

A file-scoped namespace ends with ; and covers the whole file.

See: Namespaces

Variables

int count = 3;
double ratio = 0.5;
decimal price = 9.99m;
string name = "Ada";
bool ready = true;
var label = $"{name}: {count}";

var infers the type; the m suffix makes a decimal.

See: Declarations

Literals

var million = 1_000_000;
var mask = 0b1010_0000;
var hex = 0xAB_CD;
var half = 0.5f;

_ groups digits; 0b and 0x write binary and hex.

See: Integer literals

Strings

var name = "Ada";
var greeting = $"Hi {name}";
var padded = $"{name,-6}|";
var upper = name.ToUpper();
var json = """
  { "id": 1 }
  """;

{name,-6} pads to six characters; """ keeps escapes literal.

See: String interpolation, Raw strings

Methods

static int Add(int a, int b = 0) => a + b;

static string Join(params string[] xs) =>
    string.Join(" ", xs);

Console.WriteLine(Add(2, 3));    // 5
Console.WriteLine(Join("a", "b"));  // a b

=> is an expression body; params takes any number of arguments.

See: Local functions

Types

Built-in types

Alias.NET typeExample
intInt3242
longInt6442L
doubleDouble3.14
decimalDecimal3.14m
boolBooleantrue
charChar'A'
stringString"hi"
objectObjectnew object()

string and object are reference types; the rest are value types.

See: Built-in types

Value and reference types

var p1 = new Point { X = 1, Y = 2 };
var p2 = p1;        // copy
p2.X = 9;           // p1.X stays 1

var a = new User { Name = "Ada" };
var b = a;          // same instance
b.Name = "Bob";     // a.Name is Bob

struct Point { public int X, Y; }
class User { public string Name = ""; }

Structs copy on assignment; classes share one instance.

See: Structs, Classes

Tuples

var pair = ("Ada", 36);
Console.WriteLine(pair.Item1);   // Ada

(string Name, int Age) user = ("Ada", 36);
Console.WriteLine(user.Name);    // Ada

var (name, age) = user;

A tuple groups values positionally; names and deconstruction label them.

See: Tuple types

Conversions

int num = int.Parse("42");
bool ok = int.TryParse("abc", out int n);

double d = num;         // implicit
int back = (int)3.99;   // 3
string s = 42.ToString();

TryParse returns false instead of throwing; a cast truncates.

See: Convert a string to a number

Nullables

Enable nullability

app.csproj

<Nullable>enable</Nullable>

One file

#nullable enable

The templates enable it; warnings like CS8602 flag unchecked nulls.

See: Nullable settings

Nullable value types

int? maybe = null;
int count = maybe ?? 0;         // 0
var total = maybe.GetValueOrDefault(-1);

if (maybe is int value)
    Console.WriteLine(value);

T? lets a value type hold null; is int value matches only when there is a value.

See: Nullable value types

Nullable references

string? name = null;
var length = name?.Length;   // null
var shown = name ?? "anon";  // anon
name ??= "Ada";

?. short-circuits to null; ??= assigns when the left side is null.

See: Nullable reference types

Throw on null

string? name = null;

var safe = name ??
    throw new InvalidOperationException();

Console.WriteLine(safe);

throw is an expression, so ?? can throw instead of falling back.

See: throw expression

Collections

Lists

var items = new List<string> { "a", "b" };
items.Add("c");
items.Insert(0, "z");
items.Remove("b");

Console.WriteLine(items.Count);   // 3
Console.WriteLine(items[0]);      // z

Insert shifts later items; Count is the current length.

See: List

Collection expressions

int[] nums = [1, 2, 3];
List<string> names = ["Ada", "Bob"];
Span<char> chars = ['a', 'b'];
var rest = nums[1..];      // 2, 3

[...] builds arrays, lists and spans alike.

See: Collection expressions

Dictionaries

var ages = new Dictionary<string, int>
{
    ["Ada"] = 36,
    ["Bob"] = 41,
};

ages["Cy"] = 25;

if (ages.TryGetValue("Ada", out var age))
    Console.WriteLine(age);     // 36

var zed = ages
    .GetValueOrDefault("Zed", -1);
Console.WriteLine(zed);      // -1

TryGetValue avoids the missing-key exception; GetValueOrDefault returns a default instead.

See: Dictionary<TKey,TValue>

Iterate a dictionary

var ages = new Dictionary<string, int>
{
    ["Ada"] = 36,
    ["Bob"] = 41,
};

foreach (var (name, age) in ages)
    Console.WriteLine($"{name} {age}");

foreach (var key in ages.Keys)
    Console.WriteLine(key);

A dictionary yields key/value pairs that deconstruct in foreach.

See: KeyValuePair

LINQ

Filter and sort

var scores = new[] { 42, 7, 88, 13 };

var high = scores
    .Where(n => n >= 40)
    .OrderByDescending(n => n)
    .ToList();

Console.WriteLine(string.Join(", ", high));
// 88, 42

Chains are lazy; ToList runs the query.

See: LINQ

Select and aggregate

var scores = new[] { 42, 7, 88, 13 };

Console.WriteLine(scores.Sum());        // 150
Console.WriteLine(scores.Max());        // 88
Console.WriteLine(scores.Average());    // 37.5
Console.WriteLine(
    string.Join(", ", scores.Select(n => n * 2)));
// 84, 14, 176, 26

Select projects each item; Sum, Max and Average reduce a sequence.

See: Enumerable methods

Group items

var words = new[] { "ant", "bee", "ape", "cow" };

foreach (var group in words.GroupBy(w => w[0]))
    Console.WriteLine($"{group.Key}: {string.Join(", ", group)}");

// a: ant, ape
// b: bee
// c: cow

GroupBy yields a key and its items; group.Key is what the key selector returned.

See: GroupBy

Join lists

var cities = new[] { ("Ada", "Sydney"), ("Bob", "Perth") };
var jobs = new[] { ("Ada", "engineer"), ("Cy", "designer") };

var rows =
    from c in cities
    join j in jobs on c.Item1 equals j.Item1
    select $"{c.Item1} is {j.Item2}";

foreach (var row in rows)
    Console.WriteLine(row);   // Ada is engineer

Unmatched keys drop out; add into and DefaultIfEmpty for a left join.

See: Join operations

Remove duplicates

var tags = new[] { "a", "b", "a", "cc" };

Console.WriteLine(string.Join(", ", tags.Distinct()));
// a, b, cc

Console.WriteLine(
    string.Join(", ", tags.DistinctBy(t => t.Length)));
// a, cc

Distinct compares values; DistinctBy keeps the first item per key.

See: DistinctBy

Async

Async methods

Console.WriteLine(await FetchAsync());   // 42

static async Task<int> FetchAsync()
{
    await Task.Delay(100);
    return 42;
}

async Task<T> returns a task; await unwraps its result.

See: Asynchronous programming

Parallel tasks

var tasks = new[] { LoadAsync(1), LoadAsync(2) };
int[] results = await Task.WhenAll(tasks);

Console.WriteLine(string.Join(", ", results));
// 10, 20

static async Task<int> LoadAsync(int id)
{
    await Task.Delay(10);
    return id * 10;
}

Start tasks before awaiting to run them concurrently; WhenAll gathers the results.

See: Task.WhenAll

Async streams

await foreach (var n in CountDown())
    Console.WriteLine(n);

static async IAsyncEnumerable<int> CountDown()
{
    for (int i = 3; i > 0; i--)
    {
        await Task.Delay(10);
        yield return i;
    }
}

await foreach consumes items as they arrive, without buffering the sequence.

See: Async streams

Cancellation

using var cts = new CancellationTokenSource(100);

try
{
    await Task.Delay(5000, cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("cancelled");
}

Pass the token down; the timeout cancels the delay and throws.

See: Cancellation

Records

Declare a record

var ada = new Person("Ada", 36);
Console.WriteLine(ada);   // Person { Name = Ada, Age = 36 }

var older = ada with { Age = 37 };

public record Person(string Name, int Age);

A positional record generates a constructor, properties, equality and with.

See: Records

Record equality

var a = new Person("Ada", 36);
var b = new Person("Ada", 36);

Console.WriteLine(a == b);   // True
Console.WriteLine(a == a with { Age = 40 });   // False

public record Person(string Name, int Age);

Records compare by value, property by property.

See: Value equality

Record structs

var p = new Point(1, 2);
var q = p with { X = 3 };

Console.WriteLine(q);   // Point { X = 3, Y = 2 }

public readonly record struct Point(double X, double Y);

record struct adds value equality to a struct.

See: Record structs

Required and init

var user = new User { Name = "Ada", Age = 36 };

public class User
{
    public required string Name { get; init; }
    public int Age { get; init; }
}

required forces the initializer; init properties can only be set while constructing.

See: required

Pattern matching

Type and property patterns

object value = 42;

if (value is int n && n > 10)
    Console.WriteLine($"{n} is big");   // 42 is big

if (value is not string { Length: > 0 })
    Console.WriteLine("not text");

is tests a type and binds it; property patterns match members.

See: Patterns

Switch expressions

static string Describe(int n) => n switch
{
    0 => "zero",
    < 0 => "negative",
    > 0 and < 10 => "small",
    _ => "large",
};

Console.WriteLine(Describe(7));   // small

switch returns a value; _ is the catch-all arm.

See: Switch expression

Guards

Console.WriteLine(Classify(42));       // positive int
Console.WriteLine(Classify("hello"));  // long string
Console.WriteLine(Classify(null));     // null

static string Classify(object? o) => o switch
{
    int and > 0 => "positive int",
    string s when s.Length > 3 => "long string",
    null => "null",
    _ => "other",
};

Combine patterns with and; when adds a condition to a type pattern.

See: when, Logical patterns

List patterns

int[] xs = [1, 2, 3];

if (xs is [1, .. var rest])
    Console.WriteLine(rest.Length);   // 2

if (xs is [_, .., 3])
    Console.WriteLine("ends with 3");

.. matches any run of items; a trailing pattern matches the last item.

See: List patterns

Generics

Generic methods

static T Max<T>(T a, T b)
    where T : IComparable<T> =>
    a.CompareTo(b) >= 0 ? a : b;

Console.WriteLine(Max(3, 9));       // 9
Console.WriteLine(Max("a", "b"));   // b

Type arguments are inferred; the constraint supplies CompareTo.

See: Generics

Constraints

ConstraintAccepts
where T : classReference types
where T : structValue types
where T : notnullNon-nullable types
where T : new()A public parameterless constructor
where T : IComparable<T>Types implementing the interface
where T : UU or a type derived from it

Several constraints combine with commas, eg where T : class, new().

See: Constraints

Generic types

var box = new Box<int>(42);
Console.WriteLine(box.Value);   // 42

public class Box<T>(T value)
{
    public T Value { get; } = value;
}

A primary constructor declares class parameters on the type line.

See: Generic classes

.NET CLI

Project file

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

Nullable turns on null checks; ImplicitUsings adds common namespaces such as System.

See: MSBuild properties

Solutions

dotnet new sln -n shop
dotnet new console -o api
dotnet sln add api/api.csproj

sln add records a project in the solution; building the solution builds every project.

See: dotnet sln

Packages

dotnet package add Humanizer \
  --project api/api.csproj
dotnet package list --project api/api.csproj

add package resolves the latest version; list package prints what is installed.

See: dotnet package add

Project references

dotnet new classlib -o lib
dotnet reference add lib/lib.csproj \
  --project api/api.csproj

A project reference links two projects without a package.

See: dotnet reference add

Tests

dotnet new xunit -o tests
dotnet test tests

new xunit scaffolds an xUnit project; test builds and runs it.

See: dotnet test

Also see

0 Comments for this cheatsheet. Write yours!