Skip to content
Codewilds

C# cheat sheet

The essential C# syntax on one page. Every snippet comes from a lesson of our interactive Learn C# course — click "Practise" to write it yourself and get instant feedback.

Last updated on .

Fundamentals

C# Hello World: Your First Program

Write your first C# program with Console.WriteLine and top-level statements. Compile and run real C# in your browser — no Visual Studio or .NET SDK needed.

Console.WriteLine("Hello, World!");
Practise: C# Hello World: Your First Program

C# Variables and Data Types

Learn C# variables and data types — int, double, decimal, bool, char, string and var — with conversions, constants and the mistakes beginners make most.

string name = "Aria";
int level = 7;
double health = 92.5;
bool isAlive = true;

level = level + 1;            // variables can change
Console.WriteLine(level);     // 8
Practise: C# Variables and Data Types

C# Strings and String Interpolation

Master C# strings: string interpolation with $, format specifiers, escape sequences and essential methods like Trim, ToUpper, Replace, Substring and Split.

string hero = "Aria";
int level = 7;
Console.WriteLine($"{hero} reached level {level}!");   // Aria reached level 7!
Console.WriteLine($"Next level: {level + 1}");          // Next level: 8
Practise: C# Strings and String Interpolation

C# Operators: Arithmetic, Comparison and Logic

Learn C# operators: arithmetic, integer division, the % remainder, compound assignment, the Math class, comparisons and the logical operators && || and !.

int a = 17, b = 5;
Console.WriteLine(a + b);   // 22
Console.WriteLine(a - b);   // 12
Console.WriteLine(a * b);   // 85
Console.WriteLine(a / b);   // 3   ← integer division!
Console.WriteLine(a % b);   // 2   ← remainder
Practise: C# Operators: Arithmetic, Comparison and Logic

C# if/else, switch and Switch Expressions

Make decisions in C# with if, else if and else, the ternary operator, the switch statement and modern switch expressions with relational patterns.

int health = 35;

if (health <= 0)
{
    Console.WriteLine("Game over");
}
else if (health < 50)
{
    Console.WriteLine("Find a potion!");
}
else
{
    Console.WriteLine("Fighting fit");
}
Practise: C# if/else, switch and Switch Expressions

C# Loops: for, while, do-while and foreach

Repeat code with C# loops: the for loop, while and do-while, foreach over strings, break and continue — plus how to avoid off-by-one errors.

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine($"Round {i}");
}
// Round 1, Round 2, Round 3
Practise: C# Loops: for, while, do-while and foreach

Methods

C# Methods: Parameters and Return Values

Learn to write C# methods: parameters, return types, void methods, expression-bodied members and calling one method from another — with an interactive exercise.

public static int Square(int x)
{
    return x * x;
}
Practise: C# Methods: Parameters and Return Values

C# Method Overloading, Optional and out Parameters

Go beyond basic C# methods: overloading, optional parameters with defaults, named arguments, params arrays and out parameters with the TryParse pattern.

public static int Max(int a, int b) => a > b ? a : b;
public static int Max(int a, int b, int c) => Max(Max(a, b), c);
public static double Max(double a, double b) => a > b ? a : b;

Max(3, 9);        // first version → 9
Max(3, 9, 4);     // second version → 9
Max(2.5, 1.0);    // third version → 2.5
Practise: C# Method Overloading, Optional and out Parameters

Recursion in C#: Methods That Call Themselves

Understand recursion in C#: base cases, recursive cases, the call stack and stack overflows — then write recursive methods for powers, digits and strings.

public static long Factorial(int n)
{
    if (n == 0)
    {
        return 1;                     // base case: no further calls
    }
    return n * Factorial(n - 1);      // recursive case: a smaller problem
}
Practise: Recursion in C#: Methods That Call Themselves

Arrays & Lists

C# Arrays and the foreach Loop

Learn C# arrays: declaring, indexing, Length, ranges and Array methods — and iterate over them with the foreach loop. Practise with an interactive exercise.

int[] scores = new int[3];               // three ints, all 0
string[] heroes = { "Aria", "Bo", "Cy" }; // initializer
double[] prices = [9.99, 4.5, 12.0];     // collection expression (C# 12)
Practise: C# Arrays and the foreach Loop

C# List<T>: Resizable Lists

Use C# List<T> to store a growing collection: Add, Insert, Remove, Contains, IndexOf, Count and Sort — and avoid modifying a list inside foreach.

List<string> party = new List<string>();   // empty list of strings
var loot = new List<int> { 10, 25, 5 };    // with an initializer
List<string> spells = ["fire", "ice"];     // collection expression
Practise: C# List<T>: Resizable Lists

C# Dictionary<TKey, TValue>

Store key-value pairs with C# Dictionary<TKey, TValue>: add, look up, TryGetValue, ContainsKey, Remove, iterate with foreach and count things fast.

var prices = new Dictionary<string, decimal>
{
    ["sword"] = 120m,
    ["shield"] = 85m,
};
var ages = new Dictionary<string, int>();   // empty
Practise: C# Dictionary<TKey, TValue>

Classes & Objects

C# Classes and Objects

Learn object-oriented programming in C#: define a class with fields and methods, create objects with new, use this, and understand reference semantics.

public class Hero
{
    // fields: the data every hero has
    public string Name = "";
    public int Health = 100;
    public int Level = 1;

    // methods: what a hero can do
    public void LevelUp()
    {
        Level++;
        Health += 10;
    }

    public string Describe()
    {
        return $"{Name} (level {Level}, {Health} HP)";
    }
}
Practise: C# Classes and Objects

C# Properties: get, set, init and Validation

Learn C# properties: auto-properties, private set, init-only and computed properties, validation in setters and the C# 14 field keyword.

public class Player
{
    public string Name { get; set; } = "";   // read and write
    public int Score { get; private set; }   // anyone reads, only Player writes
    public DateOnly Joined { get; init; }    // can only be set while creating the object

    public void AddPoints(int points) => Score += points;
}

var p = new Player { Name = "Aria", Joined = new DateOnly(2025, 1, 15) };
p.AddPoints(10);
Console.WriteLine(p.Score);   // 10
// p.Score = 999;             // compile error: the setter is private
// p.Joined = ...;            // compile error: init-only
Practise: C# Properties: get, set, init and Validation

C# Constructors: Overloading, Chaining and Primary Constructors

Initialise C# objects correctly with constructors: parameters, overloading, chaining with this(...), validation, read-only properties and primary constructors.

public class Weapon
{
    public string Name { get; }
    public int Damage { get; }

    public Weapon(string name, int damage)
    {
        Name = name;
        Damage = damage < 0 ? 0 : damage;
    }
}

var axe = new Weapon("Axe", 12);
Console.WriteLine($"{axe.Name}: {axe.Damage}");   // Axe: 12
Practise: C# Constructors: Overloading, Chaining and Primary Constructors

C# static Members, const and Static Classes

Understand static in C#: static fields, properties and methods shared by all objects, const and static readonly values, factory methods and static classes.

public class Monster
{
    public static int Spawned;      // one value shared by the whole class
    public string Name;             // one value per object

    public Monster(string name)
    {
        Name = name;
        Spawned++;                  // instance code can use static members
    }
}

new Monster("Goblin");
new Monster("Troll");
Console.WriteLine(Monster.Spawned);   // 2 — accessed through the class name
Practise: C# static Members, const and Static Classes

Inheritance & Interfaces

C# Inheritance: virtual, override and base

Learn inheritance in C#: derive classes with :, call base constructors, use protected members, and customise behaviour with virtual, override and sealed.

public class Character
{
    public string Name { get; }
    public int Health { get; protected set; }

    public Character(string name, int health)
    {
        Name = name;
        Health = health;
    }

    public void TakeDamage(int amount) => Health = Math.Max(0, Health - amount);
}

public class Archer : Character
{
    public int Arrows { get; private set; } = 20;

    public Archer(string name) : base(name, 90) { }

    public void Shoot() => Arrows--;
}
Practise: C# Inheritance: virtual, override and base

C# Abstract Classes and Abstract Methods

Learn abstract classes in C#: abstract methods without a body, overriding them in derived classes, and sharing code with the template method pattern.

public abstract class Enemy
{
    public string Name { get; }

    protected Enemy(string name) => Name = name;

    public abstract int Damage();              // no body: every enemy must define it

    public string Threat() => $"{Name} hits for {Damage()}";   // normal method
}
Practise: C# Abstract Classes and Abstract Methods

C# Interfaces: Contracts for Your Classes

Learn C# interfaces: declare contracts, implement several interfaces in one class, program against interface types and use is to test for capabilities.

public interface IDamageable
{
    int Health { get; }
    bool IsDestroyed { get; }
    void TakeDamage(int amount);
}
Practise: C# Interfaces: Contracts for Your Classes

Polymorphism in C#: One Interface, Many Forms

See polymorphism in C#: virtual dispatch through base-class references, collections of mixed types, type patterns with is and switch, and when to use them.

public abstract class Instrument
{
    public abstract string Play();
}

public class Drum : Instrument { public override string Play() => "Boom"; }
public class Flute : Instrument { public override string Play() => "Tweet"; }

List<Instrument> band = [new Drum(), new Flute(), new Drum()];
foreach (Instrument i in band)
{
    Console.Write(i.Play() + " ");   // Boom Tweet Boom
}
Practise: Polymorphism in C#: One Interface, Many Forms

LINQ & Errors

LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate

Learn LINQ in C#: filter with Where, transform with Select, sort with OrderBy, group with GroupBy and fold with Aggregate — plus Sum, Count, Any and First.

int[] scores = { 72, 95, 58, 88, 95 };

var passed = scores.Where(s => s >= 60);              // 72, 95, 88, 95
var curved = scores.Select(s => s + 5);               // 77, 100, 63, 93, 100
var sorted = scores.OrderByDescending(s => s);        // 95, 95, 88, 72, 58
var labels = scores.Where(s => s >= 90)
                   .Select(s => $"A ({s})")
                   .ToList();                         // ["A (95)", "A (95)"]
Practise: LINQ in C#: Where, Select, OrderBy, GroupBy and Aggregate

C# Exceptions: try, catch, finally and Custom Exceptions

Handle errors in C# with try, catch and finally, throw the right exception types, write custom exceptions and know when TryParse is the better choice.

try
{
    int level = int.Parse("forty");
    Console.WriteLine(level);
}
catch (FormatException ex)
{
    Console.WriteLine($"Not a number: {ex.Message}");
}
Practise: C# Exceptions: try, catch, finally and Custom Exceptions

C# Nullable Types and Null Safety

Write null-safe C#: nullable value types like int?, nullable reference types like string?, and the ?., ??, ??= and is null operators.

string? name = null;
Console.WriteLine(name.Length);   // 💥 NullReferenceException
Practise: C# Nullable Types and Null Safety