C# 14 cheatsheet

C# 14: Basics

9 common C# 14 tasks.

Write a program without a Main method

Top-level statements: the file's statements are the program. Implicit usings bring in common namespaces.

Console.WriteLine("Hello, world!");

Declare variables

Use var when the type is obvious. const values must be known at compile time.

var count = 3;
const double Pi = 3.14159;
string name = "Ada";

Insert values into a string

Prefix a string with $ and put expressions in braces, with an optional format.

var message = $"{name} scored {score:P1} on {DateTime.Now:yyyy-MM-dd}";

Write multi-line text

Raw string literals keep quotes and line breaks as written, with no escaping.

var json = """
    { "name": "Ada", "age": 36 }
    """;

Handle null safely

Mark possibly-null reference types with ?. The compiler warns when you dereference them.

string? nickname = null;
int length = nickname?.Length ?? 0;

Assign only when null

Assign a default if a variable is currently null.

cache ??= new Dictionary<string, int>();

Return several values

Tuples group values without defining a type, and can be deconstructed.

(int Min, int Max) Range(int[] values) => (values.Min(), values.Max());

var (min, max) = Range([3, 9, 1]);

Write a local function

Define a helper inside a method, where only that method can use it.

int Total(int[] items)
{
    return Sum(items);
    static int Sum(int[] xs) => xs.Sum();
}

Get a name as a string

Refer to variables and members without hard-coding their names.

ArgumentNullException.ThrowIfNull(user);
Console.WriteLine(nameof(user));

Was this page helpful?