C# Cheatsheet
C#
16 views
Apr 2026
Data Types
| Type | Size | Range / Notes | Example |
|---|---|---|---|
int | 32-bit | -2,147,483,648 to 2,147,483,647 | int x = 42; |
long | 64-bit | ±9.2 × 10¹⸠| long x = 9_000_000_000L; |
double | 64-bit | ~15 decimal digits | double x = 3.14; |
decimal | 128-bit | 28-29 significant digits, no float error | decimal price = 9.99m; |
bool | 1-bit | true / false | bool isReady = true; |
char | 16-bit | Unicode character | char c = 'A'; |
string | ref type | Immutable sequence of chars | string s = "hello"; |
var | — | Implicitly typed (compile-time) | var list = new List<int>(); |
object | ref type | Base type of everything | object o = 42; |
dynamic | — | Resolved at runtime | dynamic d = "hello"; |
Variables & Constants
// Declaration
int age = 30;
var name = "Alice"; // inferred as string
const double PI = 3.14159; // compile-time constant
readonly int max = 100; // runtime constant (set in constructor)
// String interpolation
string msg = $"Hello, {name}! You are {age} years old.";
// Verbatim string (raw backslashes)
string path = @"C:\Users\Alice\Documents";
// Raw string literal (C# 11+)
string json = """
{ "name": "Alice" }
""";
// Nullable types
int? nullableInt = null;
string? nullableStr = null;
Control Flow
// if / else if / else
if (age >= 18) { Console.WriteLine("Adult"); }
else if (age >= 13) { Console.WriteLine("Teen"); }
else { Console.WriteLine("Child"); }
// Ternary
string label = age >= 18 ? "Adult" : "Minor";
// Null-coalescing
string display = nullableStr ?? "default";
string? upper = nullableStr?.ToUpper(); // null if nullableStr is null
nullableStr ??= "fallback"; // assign if null
// switch expression (C# 8+)
string grade = score switch {
>= 90 => "A",
>= 80 => "B",
>= 70 => "C",
_ => "F"
};
// Pattern matching
if (obj is string s && s.Length > 0) { }
if (shape is Circle { Radius: > 10 } c) { }
// for / foreach / while / do-while
for (int i = 0; i < 10; i++) { }
foreach (var item in collection) { }
while (condition) { }
do { } while (condition);
Collections
// Array
int[] nums = { 1, 2, 3 };
int[] sized = new int[5];
// List<T>
var list = new List<string> { "a", "b", "c" };
list.Add("d");
list.Remove("a");
list.Contains("b"); // true
list.Count; // 3
// Dictionary<K,V>
var dict = new Dictionary<string, int> {
["apple"] = 1,
["banana"] = 2
};
dict.TryGetValue("apple", out int val);
dict.ContainsKey("cherry"); // false
// HashSet<T> — unique values, O(1) lookup
var set = new HashSet<int> { 1, 2, 3 };
// Queue / Stack
var queue = new Queue<string>();
queue.Enqueue("first"); queue.Dequeue();
var stack = new Stack<int>();
stack.Push(1); stack.Pop();
LINQ (Common Operations)
var nums = new[] { 1, 2, 3, 4, 5, 6 };
nums.Where(x => x % 2 == 0) // [2, 4, 6]
.Select(x => x * x) // [4, 16, 36]
.OrderByDescending(x => x) // [36, 16, 4]
.ToList();
nums.First(); // 1
nums.FirstOrDefault(x => x > 10); // 0 (default)
nums.Any(x => x > 5); // true
nums.All(x => x > 0); // true
nums.Count(x => x % 2 == 0); // 3
nums.Sum(); // 21
nums.Max(); nums.Min(); nums.Average();
// GroupBy
var grouped = people.GroupBy(p => p.City)
.Select(g => new { City = g.Key, Count = g.Count() });
// Join
var result = orders.Join(customers,
o => o.CustomerId,
c => c.Id,
(o, c) => new { o.OrderId, c.Name });
Classes & Records
// Class
public class Person {
public string Name { get; set; }
public int Age { get; init; } // init-only (C# 9+)
public Person(string name, int age) {
Name = name; Age = age;
}
public override string ToString() => $"{Name} ({Age})";
}
// Record — immutable value-semantic class (C# 9+)
public record Point(double X, double Y);
var p1 = new Point(1, 2);
var p2 = p1 with { Y = 5 }; // non-destructive mutation
// Interface
public interface IAnimal {
string Name { get; }
void Speak();
string Describe() => $"I am {Name}"; // default impl (C# 8+)
}
// Inheritance
public class Dog : Animal, IAnimal {
public override void Speak() => Console.WriteLine("Woof");
}
Async / Await
// Basic async method
public async Task<string> FetchDataAsync(string url) {
using var client = new HttpClient();
return await client.GetStringAsync(url);
}
// Async with cancellation
public async Task<List<User>> GetUsersAsync(CancellationToken ct) {
await Task.Delay(100, ct);
return await _db.Users.ToListAsync(ct);
}
// Run multiple tasks in parallel
var (r1, r2) = await (Task1Async(), Task2Async());
var results = await Task.WhenAll(tasks);
// Fire and forget (careful — exceptions are swallowed)
_ = DoSomethingAsync();
Exception Handling
try {
int result = int.Parse("abc");
}
catch (FormatException ex) {
Console.WriteLine($"Format error: {ex.Message}");
}
catch (Exception ex) when (ex.Message.Contains("timeout")) {
// Exception filters (C# 6+)
}
finally {
// Always runs
}
// throw without losing stack trace
catch (Exception ex) {
_logger.LogError(ex, "Something failed");
throw; // NOT: throw ex;
}
String Methods
string s = " Hello, World! ";
s.Trim(); // "Hello, World!"
s.ToUpper(); s.ToLower();
s.Contains("World"); // true
s.StartsWith("He"); // (after trim) true
s.Replace("World", "C#");
s.Split(','); // ["Hello", " World!"]
s.Substring(7, 5); // "World"
s.IndexOf("W"); // 7 (after trim)
string.IsNullOrWhiteSpace(s); // false
string.Join(", ", list); // "a, b, c"
// StringBuilder for heavy concatenation
var sb = new StringBuilder();
sb.Append("Hello").Append(", ").Append("World");
string result = sb.ToString();
Common Patterns
// Null-safe navigation chain
int? len = user?.Address?.City?.Length;
// Deconstruction
var (x, y) = point;
var (first, _, third) = (1, 2, 3); // discard _
// Using statement (IDisposable)
using var stream = File.OpenRead("data.txt");
// stream disposed automatically
// Local functions
int Add(int a, int b) => a + b;
// Expression-bodied members
public string FullName => $"{First} {Last}";
public void Print() => Console.WriteLine(FullName);