C# / .NET MEGA REFERENCE

C#
Cheat Sheet

A massive searchable, copy-ready C# and .NET reference covering syntax, OOP, collections, LINQ, async/await, files, JSON, regex, concurrency, reflection, testing, ASP.NET Core, Entity Framework Core, .NET CLI, and more.

442 commands & snippets
47 sections
1 standalone HTML file
C# note: This sheet targets modern C# and .NET. Some framework examples such as xUnit and Entity Framework Core require NuGet packages. Commands marked with ⚠ can delete files or directories.
Console.WriteLine("Hello, world!");

Print a line to the console.

Console.Write("Hello");

Print without a trailing newline.

int age = 18;

Declare an integer variable.

double price = 19.99;

Declare a double.

bool enabled = true;

Declare a Boolean.

char grade = 'A';

Declare a character.

string name = "Ada";

Declare a string.

var count = 10;

Use local type inference.

const double Pi = 3.14159;

Declare a compile-time constant.

object value = 42;

Store a value as object.

dynamic value = 42;

Use dynamic runtime binding.

int? maybeAge = null;

Declare a nullable value type.

string? maybeName = null;

Declare a nullable reference type when enabled.

// comment

Single-line comment.

/* multi-line comment */

Block comment.

typeof(int)

Get a Type object at compile time.

value.GetType()

Get an object's runtime type.

int.Parse("42")

Parse a string as int.

int.TryParse("42", out int n)

Safely attempt integer parsing.

Convert.ToInt32("42")

Convert a value to int.

Convert.ToString(123)

Convert a value to string.

double.Parse("3.14")

Parse a double.

(int)3.9

Explicit numeric cast.

double x = 10;

Implicit numeric conversion from int to double.

value is string

Check runtime type.

value as string

Safe reference cast returning null on failure.

a + b

Addition.

a - b

Subtraction.

a * b

Multiplication.

a / b

Division.

a % b

Remainder.

a == b

Equality.

a != b

Inequality.

a > b

Greater than.

a >= b

Greater than or equal.

a && b

Logical AND.

a || b

Logical OR.

!a

Logical NOT.

a ?? b

Null-coalescing operator.

a ??= b

Assign only if null.

condition ? yes : no

Ternary conditional.

Math.Abs(-8)

Absolute value.

Math.Max(a, b)

Maximum.

Math.Min(a, b)

Minimum.

Math.Pow(2, 8)

Exponentiation.

Math.Sqrt(81)

Square root.

Math.Round(3.14159, 2)

Round to two decimal places.

Math.Floor(3.9)

Round down.

Math.Ceiling(3.1)

Round up.

string text = "hello";

Create a string.

text.Length

Get string length.

text[0]

Get first character.

text.Substring(1, 3)

Extract part of a string.

text.ToUpper()

Convert to uppercase.

text.ToLower()

Convert to lowercase.

text.Trim()

Remove surrounding whitespace.

text.TrimStart()

Remove leading whitespace.

text.TrimEnd()

Remove trailing whitespace.

text.Contains("cat")

Check substring presence.

text.StartsWith("pre")

Check prefix.

text.EndsWith(".txt")

Check suffix.

text.IndexOf("cat")

Find first substring index.

text.Replace("old", "new")

Replace text.

text.Split(",")

Split into an array.

string.Join(", ", items)

Join strings.

$"Hello {name}"

String interpolation.

$"{price:F2}"

Format a number with two decimal places.

@"C:\Temp\file.txt"

Verbatim string literal.

"""multi-line text"""

Raw string literal in modern C#.

string.IsNullOrEmpty(text)

Check null or empty.

string.IsNullOrWhiteSpace(text)

Check null, empty, or whitespace.

int[] nums = { 1, 2, 3 };

Create and initialize an array.

string[] names = new string[5];

Create a fixed-size array.

nums[0]

Get first element.

nums[^1]

Get last element using index-from-end.

nums[1..3]

Slice with a range.

nums.Length

Get array length.

Array.Sort(nums);

Sort in place.

Array.Reverse(nums);

Reverse in place.

Array.IndexOf(nums, 3)

Find the first index.

Array.Copy(source, dest, length);

Copy array contents.

Array.Clear(nums);

Reset array elements to default values.

var items = new List<string>();

Create a mutable generic list.

var items = new List<int> { 1, 2, 3 };

Create and initialize a list.

items.Add("x");

Append an item.

items.AddRange(other);

Append multiple items.

items.Insert(0, "x");

Insert at an index.

items[0]

Read by index.

items.Remove("x");

Remove first matching value.

items.RemoveAt(0);

Remove by index.

items.Contains("x")

Check membership.

items.IndexOf("x")

Find first index.

items.Count

Get list size.

items.Sort();

Sort in place.

items.Reverse();

Reverse in place.

items.Clear();

Remove all items.

var dict = new Dictionary<string,int>();

Create a dictionary.

dict["Ada"] = 18;

Add or update a key.

dict["Ada"]

Read by key.

dict.TryGetValue("Ada", out int age)

Safely read a value.

dict.ContainsKey("Ada")

Check key existence.

dict.ContainsValue(18)

Check value existence.

dict.Remove("Ada");

Remove a key.

dict.Keys

Get keys.

dict.Values

Get values.

dict.Count

Get entry count.

var set = new HashSet<int>();

Create a hash set.

set.Add(1);

Add a unique value.

set.Contains(1)

Check set membership.

set.Remove(1);

Remove a set value.

set.UnionWith(other);

Union with another set.

set.IntersectWith(other);

Intersect with another set.

var queue = new Queue<string>();

Create a queue.

queue.Enqueue("x");

Add to queue.

queue.Dequeue()

Remove and return front item.

queue.Peek()

Read front item.

var stack = new Stack<string>();

Create a stack.

stack.Push("x");

Push an item.

stack.Pop()

Pop an item.

stack.Peek()

Read top item.

if (x > 0) { }

Basic if statement.

if (x > 0) { } else { }

if/else.

if (x > 0) { } else if (x == 0) { } else { }

if/else-if/else.

string status = age >= 18 ? "adult" : "minor";

Ternary expression.

switch (value) { case 1: break; default: break; }

Classic switch.

var result = value switch { 1 => "one", _ => "other" };

Switch expression.

if (value is null) { }

Check for null.

if (value is not null) { }

Check for non-null.

if (obj is string s) { Console.WriteLine(s.Length); }

Pattern-match type and bind variable.

for (int i = 0; i < 10; i++) { }

Classic for loop.

foreach (var item in items) { }

Loop over a collection.

while (condition) { }

Repeat while condition is true.

do { } while (condition);

Run at least once.

break;

Exit nearest loop or switch.

continue;

Skip to next iteration.

static int Add(int a, int b) => a + b;

Expression-bodied method.

static int Add(int a, int b) { return a + b; }

Block-bodied method.

void Log(string message = "default") { }

Method with default parameter.

void Print(params string[] values) { }

Variable-length parameter list.

void Update(ref int x) { x++; }

Pass by reference.

void GetValue(out int x) { x = 42; }

Output parameter.

void Read(in int x) { }

Read-only reference parameter.

return value;

Return a value.

class User { }

Define a class.

var u = new User();

Create an object.

class User { public string Name; }

Define a field.

u.Name = "Ada";

Assign a field.

class User { public User(string name) { Name = name; } }

Define a constructor.

this.Name = name;

Refer to current instance member.

public string Name { get; set; }

Auto-implemented property.

public string Name { get; init; }

Init-only property.

public string Name => _name;

Expression-bodied read-only property.

public override string ToString() => Name;

Override string representation.

class Admin : User { }

Create a subclass.

public Admin(string name) : base(name) { }

Call base constructor.

interface IPrintable { void Print(); }

Define an interface.

class Report : IPrintable { public void Print() { } }

Implement an interface.

abstract class Shape { public abstract double Area(); }

Define an abstract class.

sealed class FinalType { }

Prevent inheritance.

public virtual void Run() { }

Allow overriding.

public override void Run() { }

Override a virtual member.

public record User(string Name, int Age);

Define an immutable-style data record.

var u = new User("Ada", 18);

Create a record instance.

var older = u with { Age = 19 };

Create a modified record copy.

record struct Point(int X, int Y);

Define a record struct.

struct Point { public int X; public int Y; }

Define a value-type struct.

enum Day { Monday, Tuesday, Wednesday }

Define an enum.

Day today = Day.Monday;

Use an enum value.

Enum.Parse<Day>("Monday")

Parse enum from text.

Enum.TryParse<Day>("Monday", out var day)

Safely parse enum.

Enum.GetValues<Day>()

Get all enum values.

class Box<T> { public T Value { get; set; } }

Define a generic class.

var box = new Box<int>();

Instantiate a generic type.

static T Identity<T>(T value) => value;

Generic method.

where T : class

Constrain type parameter to reference type.

where T : struct

Constrain to non-nullable value type.

where T : new()

Require public parameterless constructor.

where T : IComparable<T>

Constrain to an interface.

Func<int,int> doubleIt = x => x * 2;

Function delegate with return value.

Action<string> log = s => Console.WriteLine(s);

Delegate returning void.

Predicate<int> positive = x => x > 0;

Predicate delegate.

x => x * 2

Single-parameter lambda.

(a, b) => a + b

Multi-parameter lambda.

() => Console.WriteLine("Hi")

No-argument lambda.

Func<int,int> square = x => x * x;

Store a lambda in a delegate.

public event EventHandler? Changed;

Declare an event.

Changed?.Invoke(this, EventArgs.Empty);

Raise an event.

obj.Changed += Handler;

Subscribe to an event.

obj.Changed -= Handler;

Unsubscribe from an event.

void Handler(object? sender, EventArgs e) { }

Basic event handler.

items.Where(x => x > 0)

Filter a sequence.

items.Select(x => x * 2)

Transform a sequence.

items.OrderBy(x => x)

Sort ascending.

items.OrderByDescending(x => x)

Sort descending.

items.ThenBy(x => x.Name)

Secondary sort.

items.Distinct()

Remove duplicates.

items.Skip(10)

Skip initial elements.

items.Take(10)

Take first elements.

items.First()

Get first item; throws if empty.

items.FirstOrDefault()

Get first item or default.

items.Single()

Require exactly one item.

items.SingleOrDefault()

Require zero or one item.

items.Any()

Check whether sequence has any elements.

items.Any(x => x.Active)

Check whether any item matches.

items.All(x => x.Active)

Check whether all items match.

items.Contains(value)

Membership test.

items.Count()

Count elements.

items.Sum()

Sum numeric elements.

items.Average()

Average numeric elements.

items.Min()

Minimum.

items.Max()

Maximum.

items.GroupBy(x => x.Category)

Group by key.

items.ToDictionary(x => x.Id)

Build a dictionary.

items.ToLookup(x => x.Category)

Build a one-to-many lookup.

items.SelectMany(x => x.Children)

Flatten nested sequences.

items.Aggregate((a, b) => a + b)

Reduce sequence to one value.

items.Zip(other, (a,b) => (a,b))

Pair two sequences.

items.Chunk(100)

Split sequence into fixed-size chunks on modern .NET.

items.DistinctBy(x => x.Id)

Remove duplicates by key on modern .NET.

items.MaxBy(x => x.Score)

Get element with maximum key.

items.MinBy(x => x.Score)

Get element with minimum key.

var q = from x in items where x > 0 select x;

LINQ query syntax.

var q = from u in users orderby u.Name select u;

Query syntax with ordering.

var q = from u in users group u by u.Department;

Query syntax grouping.

var q = from u in users join o in orders on u.Id equals o.UserId select new { u, o };

Query syntax join.

value?.Property

Null-conditional member access.

array?[0]

Null-conditional index access.

value ?? fallback

Use fallback for null.

value ??= fallback;

Assign fallback if null.

value!.Length

Null-forgiving operator; suppresses nullable warning.

string? text = null;

Nullable reference variable.

try { Risky(); } catch (IOException ex) { }

Catch a specific exception.

try { } catch (Exception ex) { }

Catch general exceptions.

try { } finally { Cleanup(); }

Always run cleanup.

throw new InvalidOperationException("Bad state");

Throw an exception.

throw;

Re-throw current exception preserving stack.

ex.Message

Read exception message.

ex.StackTrace

Read stack trace.

class AppException : Exception { }

Create a custom exception.

File.ReadAllText("file.txt")

Read an entire text file.

File.WriteAllText("file.txt", "hello");

Write text to a file.

File.AppendAllText("file.txt", "more");

Append text.

File.ReadAllLines("file.txt")

Read all lines.

File.WriteAllLines("file.txt", lines);

Write lines.

File.Exists("file.txt")

Check whether a file exists.

File.Copy("a.txt", "b.txt", true);

Copy a file and overwrite destination.

File.Move("old.txt", "new.txt");

Move or rename a file.

File.Delete("file.txt");

Delete a file. ⚠

Directory.Exists("C:\\Temp")

Check whether a directory exists.

Directory.CreateDirectory("C:\\Temp\\Logs");

Create directories.

Directory.GetFiles("C:\\Temp")

List files.

Directory.GetDirectories("C:\\Temp")

List directories.

Directory.Delete("C:\\Temp", true);

Delete a directory tree. ⚠

Path.Combine("C:\\Temp", "file.txt")

Combine path segments safely.

Path.GetFileName(path)

Get file name.

Path.GetExtension(path)

Get extension.

using var fs = File.OpenRead("file.bin");

Open a file stream for reading.

using var fs = File.Create("file.bin");

Create a writable file stream.

using var reader = new StreamReader("file.txt");

Open text reader.

string? line = reader.ReadLine();

Read one line.

using var writer = new StreamWriter("file.txt");

Open text writer.

writer.WriteLine("hello");

Write a line.

await File.ReadAllTextAsync("file.txt")

Read a file asynchronously.

await File.WriteAllTextAsync("file.txt", text)

Write a file asynchronously.

using System.Text.Json;

Import built-in JSON support.

JsonSerializer.Serialize(obj)

Serialize an object to JSON.

JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true })

Pretty-print JSON.

JsonSerializer.Deserialize<User>(json)

Deserialize JSON.

JsonDocument.Parse(json)

Parse JSON for DOM-style traversal.

element.GetProperty("name").GetString()

Read a JSON property.

[JsonPropertyName("user_name")]

Map a property to a custom JSON name.

DateTime.Now

Current local date/time.

DateTime.UtcNow

Current UTC date/time.

DateTime.Today

Current local date at midnight.

DateTimeOffset.Now

Current date/time with offset.

DateOnly.FromDateTime(DateTime.Now)

Extract date-only value.

TimeOnly.FromDateTime(DateTime.Now)

Extract time-only value.

DateTime.Parse("2026-09-18")

Parse a date/time string.

DateTime.TryParse(text, out var dt)

Safely parse date/time.

DateTime.Now.AddDays(7)

Add seven days.

end - start

Subtract DateTime values to get TimeSpan.

TimeSpan.FromMinutes(5)

Create a time span.

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Format date/time.

using System.Text.RegularExpressions;

Import regex support.

Regex.IsMatch(text, @"\d+")

Test whether pattern matches.

Regex.Match(text, @"\d+")

Get first match.

Regex.Matches(text, @"\b\w+\b")

Get all matches.

Regex.Replace(text, @"\s+", " ")

Replace regex matches.

Regex.Split(text, @"[,;]")

Split using regex.

match.Groups[1].Value

Read capture group.

async Task MainAsync() { }

Define an async method.

await Task.Delay(1000);

Pause asynchronously.

var result = await GetDataAsync();

Await an async result.

Task<int> GetValueAsync() => Task.FromResult(42);

Return an already-computed async result.

await Task.WhenAll(task1, task2);

Wait for all tasks.

await Task.WhenAny(task1, task2);

Wait for first completed task.

using var cts = new CancellationTokenSource();

Create cancellation source.

await Task.Delay(5000, cts.Token);

Pass a cancellation token.

cts.Cancel();

Request cancellation.

Task.Run(() => Work())

Run CPU-bound work on the thread pool.

Parallel.For(0, 10, i => Work(i));

Run loop iterations in parallel.

Parallel.ForEach(items, item => Work(item));

Parallelize collection work.

await Parallel.ForEachAsync(items, async (item, ct) => await WorkAsync(item, ct));

Async parallel iteration on modern .NET.

Task.WaitAll(tasks);

Synchronously wait for all tasks.

var t = new Thread(() => Work());

Create a dedicated thread.

t.Start();

Start a thread.

t.Join();

Wait for thread completion.

lock (gate) { }

Protect a critical section.

Monitor.Enter(gate);

Enter a monitor manually.

Monitor.Exit(gate);

Exit a monitor manually.

var mutex = new Mutex();

Create an OS-level mutex.

var sem = new SemaphoreSlim(3);

Limit concurrency.

await sem.WaitAsync();

Wait asynchronously for semaphore access.

sem.Release();

Release semaphore.

Interlocked.Increment(ref count)

Atomically increment an integer.

using var client = new HttpClient();

Create an HTTP client.

await client.GetStringAsync(url)

GET response body as text.

await client.GetAsync(url)

Send GET and return HttpResponseMessage.

await client.PostAsJsonAsync(url, data)

POST JSON using System.Net.Http.Json.

await client.GetFromJsonAsync<User>(url)

GET and deserialize JSON.

response.StatusCode

Read HTTP status.

response.IsSuccessStatusCode

Check success status.

response.EnsureSuccessStatusCode();

Throw on non-success HTTP response.

string? input = Console.ReadLine();

Read a line from the console.

Console.ReadKey();

Read one keypress.

args.Length

Number of command-line arguments.

args[0]

First command-line argument.

Environment.GetCommandLineArgs()

Get full process argument list.

Environment.OSVersion

Operating-system version.

Environment.MachineName

Computer name.

Environment.UserName

Current user name.

Environment.CurrentDirectory

Current working directory.

Environment.GetEnvironmentVariable("PATH")

Read an environment variable.

Environment.SetEnvironmentVariable("MODE", "dev")

Set an environment variable.

Environment.ProcessorCount

Logical processor count.

Environment.Exit(0);

Terminate the process.

GC.GetTotalMemory(false)

Get managed memory estimate.

GC.Collect();

Request garbage collection; usually unnecessary.

typeof(User)

Get Type metadata.

obj.GetType()

Get runtime type.

type.GetProperties()

List properties.

type.GetMethods()

List methods.

type.GetFields()

List fields.

type.GetConstructors()

List constructors.

Activator.CreateInstance(type)

Create an instance dynamically.

property.GetValue(obj)

Read property reflectively.

property.SetValue(obj, value)

Set property reflectively.

[Obsolete]

Mark an API as obsolete.

[Flags]

Mark enum as bit flags.

[Serializable]

Mark a type serializable for compatible serializers.

[AttributeUsage(AttributeTargets.Class)]

Control custom attribute usage.

class MyAttribute : Attribute { }

Create a custom attribute.

(int x, int y) point = (10, 20);

Create a named tuple.

var (x, y) = point;

Deconstruct a tuple.

return (name, age);

Return multiple values using a tuple.

Dictionary<(int,int), string>

Use a tuple as a dictionary key.

if (obj is string s) { }

Type pattern.

if (x is > 0 and < 10) { }

Relational/logical pattern.

var result = value switch { null => "none", string s => s, _ => "other" };

Pattern-based switch expression.

if (user is { Age: >= 18, Active: true }) { }

Property pattern.

if (items is [1, 2, ..]) { }

List pattern in modern C#.

dotnet --info

Show .NET SDK/runtime information.

dotnet --list-sdks

List installed SDKs.

dotnet new console -n App

Create a console project.

dotnet new classlib -n Library

Create a class library.

dotnet new webapi -n Api

Create an ASP.NET Core Web API project.

dotnet build

Build the project.

dotnet run

Build and run the project.

dotnet test

Run tests.

dotnet clean

Remove build outputs.

dotnet restore

Restore NuGet packages.

dotnet add package PackageName

Add a NuGet package.

dotnet remove package PackageName

Remove a NuGet package.

dotnet list package

List package references.

dotnet publish -c Release

Publish a release build.

dotnet add package Newtonsoft.Json

Add a NuGet package.

dotnet restore

Restore packages.

dotnet list package --outdated

List outdated package references.

dotnet nuget locals all --clear

Clear NuGet caches.

[Fact] public void AddsNumbers() { Assert.Equal(4, 2 + 2); }

Basic xUnit test.

Assert.Equal(expected, actual);

Assert equality in xUnit.

Assert.True(condition);

Assert true.

Assert.False(condition);

Assert false.

Assert.Null(value);

Assert null.

Assert.NotNull(value);

Assert non-null.

Assert.Throws<InvalidOperationException>(() => Func());

Assert an exception.

[Theory]

Mark a parameterized xUnit test.

[InlineData(1,2,3)]

Provide inline test data.

dotnet test

Run project tests.

var builder = WebApplication.CreateBuilder(args);

Create an ASP.NET Core app builder.

var app = builder.Build();

Build the web application.

app.MapGet("/", () => "Hello");

Map a minimal GET endpoint.

app.MapPost("/users", (User user) => Results.Ok(user));

Map a POST endpoint.

app.Run();

Start the web application.

builder.Services.AddControllers();

Register MVC/Web API controllers.

app.MapControllers();

Map attribute-routed controllers.

[ApiController]

Mark a Web API controller.

[Route("api/[controller]")]

Set controller route template.

[HttpGet]

Mark a GET action.

[HttpPost]

Mark a POST action.

builder.Services.AddSingleton<IMyService, MyService>();

Register a singleton service.

builder.Services.AddScoped<IMyService, MyService>();

Register one service instance per request scope.

builder.Services.AddTransient<IMyService, MyService>();

Create a new service instance per resolution.

public MyController(IMyService service) { _service = service; }

Constructor injection.

dotnet add package Microsoft.EntityFrameworkCore.Sqlite

Add EF Core SQLite provider.

public class AppDbContext : DbContext { public DbSet<User> Users => Set<User>(); }

Define a DbContext.

builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite("Data Source=app.db"));

Register SQLite DbContext.

await db.Users.ToListAsync()

Query all users asynchronously.

await db.Users.FindAsync(id)

Find by primary key.

db.Users.Add(user);

Track a new entity.

await db.SaveChangesAsync();

Persist tracked changes.

db.Users.Remove(user);

Mark an entity for deletion.

await db.Users.Where(x => x.Active).ToListAsync()

Filter entities with LINQ.

dotnet ef migrations add InitialCreate

Create a migration.

dotnet ef database update

Apply migrations.

ILogger<MyClass> logger

Inject a typed logger.

logger.LogInformation("Started");

Write informational log.

logger.LogWarning("Something odd");

Write warning.

logger.LogError(ex, "Operation failed");

Log exception with error message.

logger.LogDebug("Value {Value}", value);

Structured debug logging.

var unique = items.Distinct().ToList();

Remove duplicates.

var sum = nums.Sum();

Sum numbers.

var avg = nums.Average();

Average numbers.

var max = nums.Max();

Maximum value.

var longest = items.MaxBy(x => x.Length);

Find longest string on modern .NET.

var lookup = items.ToDictionary(x => x.Id);

Index objects by ID.

var grouped = items.GroupBy(x => x.Category).ToDictionary(g => g.Key, g => g.ToList());

Group into a dictionary.

var counts = items.GroupBy(x => x).ToDictionary(g => g.Key, g => g.Count());

Count repeated values.

var flat = matrix.SelectMany(x => x).ToList();

Flatten nested sequences.

var clone = JsonSerializer.Deserialize<MyType>(JsonSerializer.Serialize(obj));

Simple JSON round-trip clone for compatible types.

var text = string.Join(" ", input.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries));

Normalize repeated whitespace.

var first = items.FirstOrDefault(predicate);

Get first match or default.

ReferenceEquals(a, b)

Checks whether two references point to the same object, not logical equality.

== on custom classes

Behavior depends on whether the type overloads equality; often use Equals for semantic comparison.

async void

Avoid except for event handlers because callers cannot await it.

Task.Result / Task.Wait()

Can block threads and may deadlock in some contexts; prefer await.

new HttpClient() per request

Repeated creation can exhaust sockets; prefer reuse or IHttpClientFactory.

List<T> from multiple threads

List<T> is not thread-safe for concurrent mutation.

catch (Exception) { }

Avoid swallowing exceptions without handling or logging.

GC.Collect()

Manual garbage collection is usually counterproductive.

DateTime.Now for distributed timestamps

Prefer UTC or DateTimeOffset for cross-system timestamps.

float/double for money

Prefer decimal for exact base-10 financial calculations.