Skip to main content
Quick Reference

C# Programming Cheatsheet

Modern C# on one page — dotnet CLI, types and null, operators, control flow, strings, collections and LINQ, methods, classes and records, exceptions, async, files and JSON, and interview traps. Built for revision and for looking things up while you code.

12 sections 10 tables 27 code snippets

Program Structure & dotnet CLI

Top-level program

var name = "Ravi";
Console.WriteLine("Hello, " + name);

static string Greet(string who) => "Hi, " + who;

Console.WriteLine(Greet(name));

Create, build, run, test

dotnet new console -n Hello
dotnet run
dotnet build
dotnet test
dotnet add package Newtonsoft.Json
dotnet --version

Classic entry point

namespace Hello;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(args.Length);
    }
}

Project file essentials

<!-- Hello.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
</Project>

Keep <Nullable>enable</Nullable>. It turns forgotten null checks into compiler warnings instead of runtime NullReferenceExceptions.

Types, Variables & Null

Common declarations

int n = 42;
double price = 19.5;
decimal money = 19.50m;
bool ok = true;
char grade = 'A';
string name = "Ada";
int? maybe = null;
var items = new List<string> { "a", "b" };

Nullable references

string? title = null;
int length = title?.Length ?? 0;

if (title is not null)
{
    Console.WriteLine(title.ToUpper());
}

Value vs reference

KindExamplesNotes
Valueint, bool, double, decimal, structCopied on assignment
Referencestring, class, arraysVariables hold a reference
Nullable valueint?Value or null. Shortcut for Nullable<int>
Nullable referencestring?Compiler tracks possible null
varvar n = 1;Still a real type. Inferred, not dynamic
constconst int Max = 10;Compile-time constant

Use decimal for money. double is a binary float and 0.1 + 0.2 is not 0.3.

Operators & Patterns

Null helpers

string label = title ?? "untitled";
title ??= "untitled";
int len = user?.Name?.Length ?? 0;

string text = name is string s ? s : "";

Checks

if (value is int n && n > 0)
{
    Console.WriteLine(n);
}

if (obj is User { Age: >= 18 } user)
{
    Console.WriteLine(user.Name);
}

Operator cheat

OpMeaning
??Left side when it is not null
??=Assign only when the left side is null
?.Member access that stops on null
is / is notType test or pattern
asCast that returns null instead of throwing
nameof(x)The identifier as a string. Safe for renames
=>Expression-bodied member or lambda

Control Flow

if / else

string grade;
if (score >= 90) grade = "A";
else if (score >= 80) grade = "B";
else grade = "C";

switch expression

string label = status switch
{
    200 or 201 => "ok",
    404 => "missing",
    _ => "other",
};

Loops

for (int i = 0; i < 3; i++)
{
    Console.Write(i);
}

foreach (var user in users)
{
    Console.WriteLine(user.Name);
}

switch statement vs expression

StatementExpression
ResultRuns statementsProduces a value
Armscase + breakpattern => value
No matchDoes nothingThrows if there is no _
PatternsType, constant, relationalSame, often shorter

Strings

Build and search

string name = "Ravi";
string hello = "Hello, " + name;
string formatted = string.Format("id={0:D4}", 7);

string trimmed = "  hi  ".Trim();
string[] parts = "a,b,c".Split(',');
string line = string.Join("-", parts);
bool has = text.Contains("csharp", StringComparison.OrdinalIgnoreCase);

Ranges and compare

string word = "cheatsheet";
string mid = word[1..5];          // heat
bool same = string.Equals(
    "Ada",
    "ada",
    StringComparison.OrdinalIgnoreCase);

ReadOnlySpan<char> span = word.AsSpan(0, 5);

Which compare

CallUse
== on stringOrdinal value compare. Null-safe
StringComparison.OrdinalByte-wise. Ids, paths, codes
OrdinalIgnoreCaseASCII case fold. Emails, headers
CurrentCultureText a person will read and sort
string.IsNullOrWhiteSpaceNull, empty, or only spaces

Arrays, Lists, Dictionaries & LINQ

Arrays, lists, dictionaries

int[] nums = [10, 20, 30];
var list = new List<int> { 1, 2, 3 };
list.Add(4);

var user = new Dictionary<string, string>
{
    ["name"] = "Ravi",
    ["city"] = "Hyderabad",
};

if (user.TryGetValue("name", out string? name))
{
    Console.WriteLine(name);
}

LINQ

var doubled = nums.Select(n => n * 2).ToList();
var adults = users.Where(u => u.Age >= 18);
int sum = nums.Sum();
var ordered = users.OrderBy(u => u.Age).ThenBy(u => u.Name);
string[] names = users.Select(u => u.Name).ToArray();

Pick a collection

TypeWhen
T[]Fixed length. Cheap and clear
List<T>Growable sequence. Default choice
Dictionary<TKey, TValue>Lookup by key. Use TryGetValue
HashSet<T>Unique items and fast contains
IEnumerable<T>A sequence you can foreach. LINQ stays lazy until you enumerate

Methods & Lambdas

Optional, params, expression body

static string Greet(string name, string title = "Hi")
{
    return title + ", " + name;
}

static int Total(params int[] nums) => nums.Sum();

var add = (int a, int b) => a + b;

out and local function

if (int.TryParse(text, out int age))
{
    Console.WriteLine(age);
}

int Clamp(int n) => Math.Clamp(n, 0, 100);

Argument forms

FormMeaning
string title = "Hi"Optional parameter. Must come after required ones
params int[] numsCaller passes a list of ints
out int ageMethod writes a result back
ref int nMethod reads and writes the caller’s variable
(int a, int b) => a + bLambda. Use for LINQ and callbacks

Classes, Records & Interfaces

Class with properties

public class User
{
    public User(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public string Name { get; }
    public int Age { get; private set; }

    public string Greet() => "Hi, " + Name;
}

Record and interface

public record Point(int X, int Y);

public interface IGreeter
{
    string Greet();
}

public enum Status
{
    Draft,
    Live,
}

Which shape

KeywordUse
classIdentity and behavior. Equality is by reference unless you write it
recordData. Value equality and a useful ToString
structSmall value type. Copy, do not share mutable state
interfaceA contract. A class can implement many
enumA closed set of named constants
abstract / virtual / overrideBase behavior a child can replace

Exceptions & using

try / catch / finally

try
{
    if (age < 0)
        throw new ArgumentOutOfRangeException(nameof(age));
}
catch (ArgumentOutOfRangeException ex)
{
    Console.Error.WriteLine(ex.Message);
}
finally
{
    // runs on success and on failure
}

using disposes

using var reader = new StreamReader(path);
string line = reader.ReadLine() ?? "";

using (var other = File.OpenRead(path))
{
    // other.Dispose() at the closing brace
}

What to throw

TypeWhen
ArgumentNullExceptionA required argument is null
ArgumentOutOfRangeExceptionA number or index is illegal
InvalidOperationExceptionThe object is in the wrong state
IOExceptionFile or stream failure
Your own typeA domain failure callers should handle

async & await

A task that returns data

static async Task<string> ReadAsync(HttpClient client, string url)
{
    return await client.GetStringAsync(url);
}

string body = await ReadAsync(client, url);

Run independent work together

Task<string> a = ReadAsync(client, left);
Task<string> b = ReadAsync(client, right);
await Task.WhenAll(a, b);

string leftBody = await a;
string rightBody = await b;

Signatures

ReturnMeaning
TaskAsync work with no result
Task<T>Async work that produces a T
ValueTask<T>Same idea when the result is often already ready
async voidOnly for event handlers. Errors are hard to catch
awaitPause this method until the task finishes. Does not block a thread by itself

Reuse one HttpClient (or IHttpClientFactory). Creating a new client per call exhausts sockets.

Files & JSON

Read and write text

string text = await File.ReadAllTextAsync("notes.txt");
await File.AppendAllTextAsync("out.txt", text + Environment.NewLine);

string[] lines = await File.ReadAllLinesAsync("notes.txt");

System.Text.Json

var json = JsonSerializer.Serialize(new { Ok = true });
var data = JsonSerializer.Deserialize<Dictionary<string, bool>>(json);

if (data is null || !data.TryGetValue("Ok", out bool ok) || !ok)
{
    throw new InvalidOperationException("unexpected JSON");
}

Property names in System.Text.Json match the C# names by default. Use [JsonPropertyName("ok")] when the JSON uses a different spelling.

Interview Traps

Traps worth memorising

TrapWhat happensPrefer
double for money0.1 + 0.2 is not 0.3decimal
== on two class instancesReference equality unless you overload itrecord, or write Equals
async voidExceptions escape the callerasync Task
Calling async without awaitWork runs, failures disappearawait or pass the Task up
new HttpClient() per requestSockets stay openOne client, or the factory
Changing a list inside foreachInvalidOperationExceptionLoop a copy, or use a for
DateTime.Now for instantsLocal time, unclear KindDateTimeOffset.UtcNow
Swallowing catch (Exception)Hides bugsCatch a specific type, or log and rethrow
Null-forgiving !Silences the compiler, not the nullCheck, or type it as non-null
using forgotten on a streamFile stays lockedusing or using var
LINQ left lazyQuery runs again on every foreach.ToList() when you need a snapshot
String compare without a comparisonCulture surprises in Turkish localesPass a StringComparison

Record equality

var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b);   // True

var c1 = new User("Ada", 20);
var c2 = new User("Ada", 20);
Console.WriteLine(ReferenceEquals(c1, c2)); // False

Lazy LINQ

IEnumerable<int> query = nums.Where(n => n > 0);
nums.Add(5);                 // included if nums is a List
foreach (int n in query) { } // runs the filter now
var snapshot = query.ToList();

How to use this page: skim the jump chips, drill the tables, then type every snippet with dotnet new console and dotnet run. Pair LINQ and async with a tiny project so the types are not abstract.