Menu

C# Cheat Sheet

Last updated

Hello World & program structure

Top-level statements (since .NET 6) let you skip the boilerplate class.

ElementCode
Top-level programConsole.WriteLine("Hello, World!");
Import a namespaceusing System;
Classic entry pointstatic void Main(string[] args) { ... }
Print a lineConsole.WriteLine("text");
Read a linestring s = Console.ReadLine();
String interpolationConsole.WriteLine($"Hi {name}");
Comments// line and /* block */

Data types

TypeDescription
int32-bit signed integer
long64-bit signed integer
double / floatFloating point numbers
decimalHigh-precision decimal (money)
booltrue or false
charSingle Unicode character
stringImmutable text
varCompiler infers the type
int?Nullable value type

Variables

OperationSyntax
Declare & initializeint x = 5;
Type inferencevar name = "Ada";
Constantconst double Pi = 3.14159;
Read-only fieldreadonly int id;
Nullable referencestring? maybe = null;
Null-coalescingvar y = maybe ?? "default";
Null-conditionalint? len = text?.Length;

Control flow

StatementSyntax
If / elseif (x > 0) { ... } else { ... }
Switch statementswitch (n) { case 1: ...; break; default: ...; }
Switch expressionvar s = n switch { 1 => "one", _ => "other" };
While loopwhile (i < n) { ... }
Do-while loopdo { ... } while (i < n);
For loopfor (int i = 0; i < n; i++) { ... }
Foreach loopforeach (var item in list) { ... }
Break / continuebreak; exits a loop, continue; skips to next iteration

Methods

OperationSyntax
Define a methodint Add(int a, int b) { return a + b; }
Expression-bodiedint Add(int a, int b) => a + b;
No return valuevoid Greet() { ... }
Optional parameterint Pow(int b, int e = 2) { ... }
Named argumentsPow(b: 2, e: 3);
Out parameterbool TryParse(string s, out int n) { ... }
Static methodstatic int Square(int x) => x * x;
Lambda expressionFunc<int, int> f = x => x * 2;

Classes & OOP

OperationSyntax
Define a classclass Dog { ... }
Auto propertypublic string Name { get; set; }
Read-only propertypublic int Id { get; }
Constructorpublic Dog(string name) { Name = name; }
Create an objectvar d = new Dog("Rex");
Inheritanceclass Puppy : Dog { ... }
Interfaceinterface IRunnable { void Run(); }
Override a methodpublic override void Speak() { ... }
Record (immutable)record Point(int X, int Y);

Collections

Generic collections from System.Collections.Generic.

TypeUse & 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();
Arrayint[] nums = { 1, 2, 3 };
Collection initializervar l = new List<int> { 1, 2, 3 };
Iterate a dictionaryforeach (var kv in dict) { kv.Key; kv.Value; }

LINQ

Query collections fluently; from System.Linq.

OperationSyntax
Filternums.Where(n => n > 0)
Project / mapnums.Select(n => n * 2)
Sortnums.OrderBy(n => n) / OrderByDescending(...)
First matchnums.First(n => n > 5) / FirstOrDefault(...)
Any / allnums.Any(n => n < 0) / nums.All(n => n > 0)
Count matchesnums.Count(n => n > 0)
Aggregatenums.Sum(), nums.Max(), nums.Average()
Group byitems.GroupBy(i => i.Category)
Materialize.ToList() / .ToArray()

Common patterns (properties, async)

PatternSyntax
Async methodasync Task<int> GetAsync() { ... }
Await a taskvar result = await GetAsync();
Try / catchtry { ... } catch (Exception e) { ... }
Finallyfinally { ... } always runs
Using (dispose)using var file = File.OpenRead(path);
String formatting$"Total: {amount:C}"
Generic classclass Box<T> { public T Value; }
Pattern matchingif (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?
Yes. This C# cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up syntax, a collection, or a LINQ method.
What is the difference between value types and reference types in C#?
Value types (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?
LINQ (Language Integrated Query) is a set of methods like 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.
Can I practice C# online?
Yes. Open the C# playground to run any snippet from this cheat sheet in your browser - no SDK to install. When you want structure, Coddy's free interactive C# course takes you from variables and loops to classes, collections, and LINQ step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common building blocks (types, control flow, methods) down to advanced ones (LINQ, async, generics), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn C# with Coddy

GET STARTED