C# Cheat Sheet
Last updated
Hello World & program structure
Top-level statements (since .NET 6) let you skip the boilerplate class.
| Element | Code |
|---|---|
| Top-level program | Console.WriteLine("Hello, World!"); |
| Import a namespace | using System; |
| Classic entry point | static void Main(string[] args) { ... } |
| Print a line | Console.WriteLine("text"); |
| Read a line | string s = Console.ReadLine(); |
| String interpolation | Console.WriteLine($"Hi {name}"); |
| Comments | // line and /* block */ |
Data types
| Type | Description |
|---|---|
int | 32-bit signed integer |
long | 64-bit signed integer |
double / float | Floating point numbers |
decimal | High-precision decimal (money) |
bool | true or false |
char | Single Unicode character |
string | Immutable text |
var | Compiler infers the type |
int? | Nullable value type |
Variables
| Operation | Syntax |
|---|---|
| Declare & initialize | int x = 5; |
| Type inference | var name = "Ada"; |
| Constant | const double Pi = 3.14159; |
| Read-only field | readonly int id; |
| Nullable reference | string? maybe = null; |
| Null-coalescing | var y = maybe ?? "default"; |
| Null-conditional | int? len = text?.Length; |
Control flow
| Statement | Syntax |
|---|---|
| If / else | if (x > 0) { ... } else { ... } |
| Switch statement | switch (n) { case 1: ...; break; default: ...; } |
| Switch expression | var s = n switch { 1 => "one", _ => "other" }; |
| While loop | while (i < n) { ... } |
| Do-while loop | do { ... } while (i < n); |
| For loop | for (int i = 0; i < n; i++) { ... } |
| Foreach loop | foreach (var item in list) { ... } |
| Break / continue | break; exits a loop, continue; skips to next iteration |
Methods
| Operation | Syntax |
|---|---|
| Define a method | int Add(int a, int b) { return a + b; } |
| Expression-bodied | int Add(int a, int b) => a + b; |
| No return value | void Greet() { ... } |
| Optional parameter | int Pow(int b, int e = 2) { ... } |
| Named arguments | Pow(b: 2, e: 3); |
| Out parameter | bool TryParse(string s, out int n) { ... } |
| Static method | static int Square(int x) => x * x; |
| Lambda expression | Func<int, int> f = x => x * 2; |
Classes & OOP
| Operation | Syntax |
|---|---|
| Define a class | class Dog { ... } |
| Auto property | public string Name { get; set; } |
| Read-only property | public int Id { get; } |
| Constructor | public Dog(string name) { Name = name; } |
| Create an object | var d = new Dog("Rex"); |
| Inheritance | class Puppy : Dog { ... } |
| Interface | interface IRunnable { void Run(); } |
| Override a method | public override void Speak() { ... } |
| Record (immutable) | record Point(int X, int Y); |
Collections
Generic collections from System.Collections.Generic.
| Type | Use & example |
|---|---|
List<T> | Dynamic array: list.Add(1); list.Count; |
Dictionary<K, V> | Key-value: dict["a"] = 1; dict.ContainsKey("a"); |
HashSet<T> | Unique values: set.Add(5); set.Contains(5); |
Queue<T> | FIFO: q.Enqueue(x); q.Dequeue(); |
Stack<T> | LIFO: s.Push(x); s.Pop(); |
| Array | int[] nums = { 1, 2, 3 }; |
| Collection initializer | var l = new List<int> { 1, 2, 3 }; |
| Iterate a dictionary | foreach (var kv in dict) { kv.Key; kv.Value; } |
LINQ
Query collections fluently; from System.Linq.
| Operation | Syntax |
|---|---|
| Filter | nums.Where(n => n > 0) |
| Project / map | nums.Select(n => n * 2) |
| Sort | nums.OrderBy(n => n) / OrderByDescending(...) |
| First match | nums.First(n => n > 5) / FirstOrDefault(...) |
| Any / all | nums.Any(n => n < 0) / nums.All(n => n > 0) |
| Count matches | nums.Count(n => n > 0) |
| Aggregate | nums.Sum(), nums.Max(), nums.Average() |
| Group by | items.GroupBy(i => i.Category) |
| Materialize | .ToList() / .ToArray() |
Common patterns (properties, async)
| Pattern | Syntax |
|---|---|
| Async method | async Task<int> GetAsync() { ... } |
| Await a task | var result = await GetAsync(); |
| Try / catch | try { ... } catch (Exception e) { ... } |
| Finally | finally { ... } always runs |
| Using (dispose) | using var file = File.OpenRead(path); |
| String formatting | $"Total: {amount:C}" |
| Generic class | class Box<T> { public T Value; } |
| Pattern matching | if (obj is Dog d) { d.Bark(); } |
The C# syntax, collections, and LINQ queries you reach for most, on one page. This C# cheat sheet is a quick reference for writing C# - the data types, control flow, classes, the List/Dictionary collections, LINQ, and the property and async patterns that define idiomatic .NET code.
Everything here is standard C# on .NET and runs with the dotnet CLI. Copy what you need, or try any snippet live in the C# playground - no SDK to install.
C# cheat sheet FAQ
Is this C# cheat sheet free?
What is the difference between value types and reference types in C#?
int, double, bool, struct, enum) hold their data directly and are copied when assigned or passed to a method - changing the copy does not affect the original. Reference types (class, string, arrays, List<T>) hold a reference to data on the heap, so two variables can point at the same object and a change through one is visible through the other. string is a reference type but behaves immutably.What is LINQ and when should I use it?
Where, Select, and OrderBy that let you filter, transform, and aggregate collections with readable, chainable calls instead of manual loops. Use it whenever you would otherwise write a loop to build a filtered or projected list - it is concise and lazily evaluated until you call ToList() or iterate.