.NET Academy

C# syntax cheat sheet

Types, control flow, classes, records, pattern matching and more on one page.

Types and variables

int i = 42;           long l = 42L;        double d = 1.5;      decimal m = 9.99m;
bool b = true;        char c = 'A';        string s = "text";   var inferred = 3.14;
const int Max = 10;   int? maybe = null;   object o = i;        // boxing
ConversionExample
Implicit (widening)double x = i;
Explicit castint n = (int)3.9; → 3
Parse / TryParseint.Parse("5"), int.TryParse(input, out var n)
To stringn.ToString(), $"{n:N2}"

Strings

$"Hi {name}, you are {age} ({price:F2} / {ratio:P0})"   // interpolation + format specifiers
@"C:\path\file.txt"                                      // verbatim
"""
  raw "string" with no escaping
  """
s.Length  s[0]  s[^1]  s[1..4]  s.ToUpper()  s.Trim()  s.Contains("x")
s.Split(',')  string.Join(", ", items)  s.Replace("a", "b")  s.StartsWith("x")
string.IsNullOrWhiteSpace(s)   new StringBuilder().Append("x").ToString()

Operators

a + b  a - b  a * b  a / b (int division!)  a % b      x++  x += 2
==  !=  <  >  <=  >=      &&  ||  !      cond ? a : b
x?.Prop   x ?? fallback   x ??= value   x!        // null operators

Control flow

if (x > 0) { } else if (x < 0) { } else { }
 
switch (day) { case "Sat": case "Sun": Weekend(); break; default: Work(); break; }
 
string label = score switch { >= 90 => "A", >= 80 => "B", _ => "F" };
 
for (int i = 0; i < n; i++) { }     while (cond) { }     do { } while (cond);
foreach (var item in items) { }     break;  continue;

Methods

int Add(int a, int b) => a + b;                          // expression-bodied
void Log(string msg, string level = "info") { }          // optional parameter
Log(level: "warn", msg: "disk");                         // named arguments
void Swap(ref int a, ref int b) { }                      // by reference
bool TryGet(int id, out string name) { name = ""; return false; }
int Sum(params int[] xs) => xs.Sum();
(int Min, int Max) Range(int[] xs) => (xs.Min(), xs.Max());   // tuple return

Classes, properties, records, structs

public class Account(string owner)                       // primary constructor
{
    public string Owner { get; } = owner;                // get-only
    public decimal Balance { get; private set; }         // private setter
    public required string Email { get; init; }          // required, init-only
    public string Label => $"{Owner} ({Balance:C})";     // computed
    public static int Count { get; private set; }        // shared by all instances
}
 
public record Point(int X, int Y);                       // value equality, with-expressions
var moved = p with { X = 5 };
public readonly record struct Rgb(byte R, byte G, byte B);
public struct Vector { public double X, Y; }             // value type

Inheritance and interfaces

public abstract class Shape { public abstract double Area(); public virtual string Name => "shape"; }
public class Circle(double r) : Shape { public override double Area() => Math.PI * r * r; }
public sealed class Square : Rectangle { public Square(double s) : base(s, s) { } }
 
public interface IRepository<T> { T? Find(int id); void Add(T item); }
public class Repo : IRepository<User>, IDisposable { ... }
ModifierAccessible from
publicEverywhere
internalSame assembly
protectedThis class and derived classes
privateThis class only (default for members)

Generics and collections

T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) >= 0 ? a : b;
 
var list = new List<int> { 1, 2 };          list.Add(3); list.Remove(1); list.Count
var map = new Dictionary<string, int>();    map["a"] = 1; map.TryGetValue("a", out var v)
var set = new HashSet<string>();            set.Add("x") /* false if present */
var queue = new Queue<int>();               queue.Enqueue(1); queue.Dequeue()
var stack = new Stack<int>();               stack.Push(1); stack.Pop()
int[] array = [1, 2, 3];                    // collection expression

Pattern matching

if (obj is Customer { IsVip: true } c) { }
if (input is not null) { }
var text = value switch
{
    null => "null",
    int n when n < 0 => "negative",
    string { Length: 0 } => "empty",
    [var first, .., var last] => $"{first}..{last}",   // list pattern (for arrays/lists)
    _ => "other",
};

Exceptions, enums, delegates

try { ... } catch (FormatException ex) when (ex.Message != "") { ... } finally { ... }
throw new ArgumentOutOfRangeException(nameof(age));    throw;   // rethrow, keep stack trace
 
enum Status { Pending, Shipped }        [Flags] enum Perm { None = 0, Read = 1, Write = 2 }
 
Func<int, int> square = x => x * x;     Action<string> log = Console.WriteLine;
public event EventHandler<OrderPlaced>? Placed;    Placed?.Invoke(this, args);