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());
} Use decimal for money. double is a binary float and 0.1 + 0.2 is not 0.3. 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);
} 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 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];
bool same = string.Equals(
"Ada",
"ada",
StringComparison.OrdinalIgnoreCase);
ReadOnlySpan<char> span = word.AsSpan(0, 5); 📚 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(); 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); 🧱 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,
} try / catch / finally try
{
if (age < 0)
throw new ArgumentOutOfRangeException(nameof(age));
}
catch (ArgumentOutOfRangeException ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
} using disposes using var reader = new StreamReader(path);
string line = reader.ReadLine() ?? "";
using (var other = File.OpenRead(path))
{
} 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; Reuse one HttpClient (or IHttpClientFactory). Creating a new client per call exhausts sockets. 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. Record equality var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b);
var c1 = new User("Ada", 20);
var c2 = new User("Ada", 20);
Console.WriteLine(ReferenceEquals(c1, c2)); Lazy LINQ IEnumerable<int> query = nums.Where(n => n > 0);
nums.Add(5);
foreach (int n in query) { }
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. |