C#C#

C# cheatsheet – syntax overview

80 key commands and patterns for quick reference.

Basics Types & conversion Operators Control flow Strings Arrays & lists Dictionary & HashSet LINQ Classes & records Errors, files & async

Basics

Console.WriteLine("Text " + x);Print with a line break
string? s = Console.ReadLine();Read a line of input (may be null)
// Comment /* Block */Comments
var x = 42;Let the compiler infer the type
const int Max = 100;Constant
$"Hello {name}, {x:F2}"String interpolation with formatting
(a, b) = (b, a);Swap values (tuple deconstruction)

Types & conversion

int long double decimal bool char stringMost important basic types
int.Parse("5") double.Parse("2.5")String to number (exception on error)
int.TryParse(s, out int n)Safe conversion, returns bool
(double)x (int)3.9Explicit cast (truncates: 3)
x.ToString() Convert.ToInt32("7")Convert to string / with Convert
x is int x as stringCheck type / convert safely (null on failure)
typeof(int) x.GetType()Query type information
int? n = null;Nullable value type

Operators

+ - * / %Arithmetic (int / int = int, % = remainder)
== != < > <= >=Comparisons
&& || !Logical operators (short-circuit)
x++ x-- x += 2Increment, decrement, compound assignment
a ?? b a ??= b a?.bNull-coalescing, assign if null, safe access
c ? x : yTernary operator
arr[^1] arr[1..3]Index from the end / range

Control flow

if (x > 0) { } else if (x == 0) { } else { }Branching
for (int i = 0; i < 5; i++) { }Counting loop
foreach (var x in liste) { }Loop over a collection
while (bedingung) { } do { } while (b);Loop with a condition
break; continue; return;Exit loop / next iteration / leave method
x switch { 1 => "a", _ => "b" }switch expression
Enumerable.Range(1, 5)Number sequence 1 to 5

Strings

s.ToUpper() s.ToLower()Upper/lower case
s.Trim() s.TrimStart() s.TrimEnd()Remove whitespace
s.Split(',') string.Join(",", arr)Split / join
s.Replace("a", "b")Replace
s.StartsWith("x") s.EndsWith("y") s.Contains("z")Check start/end/substring
s.IndexOf("x") s.Substring(2, 3) s[1..4]Search and slice
string.IsNullOrWhiteSpace(s)Empty, null or only whitespace?
"""Raw text with "Anführungszeichen" """Raw string literal (C# 11)

Arrays & lists

int[] a = { 1, 2, 3 }; int[] b = new int[5];Create an array
var l = new List<int> { 1, 2 }; List<int> m = [1, 2];Create a list (also collection expression)
l.Add(3); l.AddRange(x); l.Insert(0, 9);Add / insert
l.Remove(3); l.RemoveAt(0); l.Clear();Remove
l.Count arr.LengthNumber of elements
l.Sort(); l.Reverse();Sort / reverse (in place)
l.Contains(x) l.IndexOf(x)Contains? / position
Array.Sort(arr) Array.IndexOf(arr, x)Helper methods for arrays

Dictionary & HashSet

var d = new Dictionary<string, int> { ["a"] = 1 };Create a dictionary
d["b"] = 2; d.Add("c", 3);Set (Add throws on duplicates)
d.TryGetValue("a", out var v)Read safely
d.GetValueOrDefault("z", 0)Read with a default value
d.ContainsKey("a") d.Remove("a")Check / remove
d.Keys d.ValuesAll keys / values
var s = new HashSet<int> { 1, 2 }; s.Add(3);Set without duplicates
s.UnionWith(t) s.IntersectWith(t)Set operations

LINQ

l.Where(x => x > 1)Filter
l.Select(x => x * 2)Transform
l.OrderBy(x => x.Name).ThenBy(x => x.Alter)Sort by multiple criteria
l.Sum() l.Min() l.Max() l.Average() l.Count()Aggregation
l.First() l.FirstOrDefault() l.Single()First element / exactly one element
l.Any(x => x > 5) l.All(x => x > 0)At least one / all satisfy the condition
l.GroupBy(x => x.Stadt)Group
l.Take(3) l.Skip(2) l.Distinct()Slice / skip / remove duplicates
l.ToList() l.ToArray() l.ToDictionary(k => k.Id)Materialize the result

Classes & records

class A : Basis, IX { }Class with inheritance and interface
public string Name { get; set; }Auto-property
public required string Name { get; init; }Mandatory member, settable only during creation
public virtual void M() { } overrideOverridable method / override
record P(int X, int Y); p with { X = 5 }Record and non-destructive copy
class K(int start) { }Primary constructor (C# 12)
abstract class B { } sealed class C { }Abstract (cannot be instantiated) / sealed (cannot be inherited)
public / private / protected / internalAccess modifiers
staticBelongs to the class, not the object

Errors, files & async

try { } catch (Ex e) when (b) { } finally { }Error handling with a filter
throw new ArgumentException("Text");Raise an exception
ArgumentNullException.ThrowIfNull(x);Check a parameter for null
File.ReadAllText(p) File.WriteAllText(p, s)Read / write a whole file
File.ReadLines(p) File.Exists(p)Read line by line / check existence
using var f = new StreamReader(p);Release a resource at the end of the scope
async Task<int> M() { await Task.Delay(1); return 1; }Asynchronous method
await Task.WhenAll(t1, t2)Wait for several tasks at once
dotnet new console | run | build | testImportant CLI commands