glunty

C# Language Cheat Sheet

A searchable reference of common C# language features and what each snippet does.

Common C# language snippets with a plain-English description of what each one does
Snippet What it does
using System; Import a namespace so its types are available without full qualification.
namespace MyApp; A file-scoped namespace that groups the types declared in this file.
var name = "Ada"; Declare a local variable and let the compiler infer its type from the value.
int n = 42; A 32-bit signed integer, the default type for whole numbers.
double price = 9.99; A 64-bit floating-point number for decimal values.
bool ok = true; A Boolean value that holds only true or false.
string s = "hello"; An immutable sequence of characters written in double quotes.
$"Hi {name}, age {age}" String interpolation embeds expressions in a string using a dollar sign and braces.
const double Pi = 3.14159; A compile-time constant whose value can never change.
int? score = null; A nullable value type that can also hold null, marked with a question mark.
Console.WriteLine("Hi"); Write a line of text and a newline to standard output.
Console.WriteLine(args[0]); Top-level statements run as the program entry point without an explicit Main method.
int[] nums = {1, 2, 3}; A fixed-size array of integers with its elements listed in braces.
var list = new List<string>(); Create a dynamic list that can grow and shrink at runtime.
list.Add("item"); Append an item to the end of a list.
var ages = new Dictionary<string, int>(); Create a key-value dictionary for fast lookups by key.
ages["Sam"] = 30; Add or update a dictionary entry using its key.
foreach (var n in nums) { } Iterate over every element of a collection without an index.
nums.Where(n => n > 1) Filter a sequence to the elements matching a condition, using LINQ.
nums.Select(n => n * n) Project each element into a new form, using LINQ.
IEnumerable<int> seq = nums; The core interface that every LINQ-queryable sequence implements.
Array.Sort(nums); Sort an array in place into ascending order.
if (x > 0) { } else { } Run one block when a condition is true and another when it is false.
for (int i = 0; i < n; i++) { } Loop with an initializer, a condition, and an increment step.
foreach (var item in list) { } Loop over each element of a collection without tracking an index.
while (x < 10) { } Repeat a block while a condition stays true.
do { } while (x < 10); Run a block once, then keep repeating it while a condition holds.
switch (day) { case 1: break; } Branch to a matching case label based on a value.
day switch { 1 => "Mon", _ => "?" } A switch expression returns a value for the first matched pattern.
var s = ok ? "yes" : "no"; The ternary operator picks between two values on one line.
if (obj is string str) { } Pattern matching tests a type and binds the value to a new variable in one step.
class Dog { } Define a reference type that bundles data and behavior together.
public Dog(string name) { } A constructor is a special method that runs when a new object is created.
public string Name { get; set; } An auto-implemented property with a public getter and setter.
public int Id; private int age; Access modifiers such as public and private expose or hide members.
public static int Count; A static member belongs to the type itself rather than to any instance.
class Pup : Dog { } Derive a class from a base class to inherit its members.
interface IShape { double Area(); } An interface is a contract of members that implementing types must provide.
abstract class Shape { } An abstract class cannot be created directly and may leave methods unimplemented.
public virtual void Draw() { } Mark a method virtual so derived classes are allowed to override it.
public override string ToString() { } Override replaces an inherited virtual method with new behavior.
record Point(int X, int Y); A record is a concise reference type with value-based equality, built for data.
void Greet(string name) { } Declare a method with a name, parameters, and a body.
return a + b; Exit a method and hand a value back to the caller.
void Log(params string[] msgs) { } The params keyword accepts a variable number of arguments as one array.
void Open(bool force = false) { } An optional parameter has a default value so callers can omit it.
int Square(int x) => x * x; An expression-bodied method writes its whole body as a single expression.
T First<T>(T[] items) => items[0]; A generic method is parameterized by a type so it works with any type.
static int Twice(this int n) => n * 2; An extension method adds a method to an existing type using the this keyword.
async Task<int> GetAsync() => await F(); An async method awaits work and returns a result without blocking the thread.
Func<int, int> f = x => x + 1; A lambda expression is an inline anonymous function stored in a delegate.
try { } catch (Exception e) { } finally { } Run code, handle any error, and always run the finally cleanup block.
throw new ArgumentException("bad"); Raise an exception to signal an error condition.
catch (IOException e) { } Handle only one specific exception type.
using (var f = File.Open(p)) { } A using statement disposes a resource automatically when the block ends.
class MyError : Exception { } Define your own exception type by deriving from Exception.
catch (Exception e) when (e.Message != "") { } A when filter catches an exception only when its condition is true.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for the C# syntax you reach for most, from basic types and string handling to collections, LINQ, control flow, classes, methods, and error handling. Each row pairs a small snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering LINQ surfaces the query methods; entering async jumps to the asynchronous snippets; entering record shows the value-based data type. The category buttons (Basics, Collections, Control flow, OOP, Methods, Exceptions) narrow the table to one family and combine with the text filter, so you can pick Collections and type Dictionary to zero in on key-value lookups. Clear the box to see the full sheet again.

Common use cases

  • Recalling the exact shape of a snippet you use rarely, like a switch expression or an extension method.
  • Copying correct syntax into your editor instead of guessing.
  • Teaching a teammate the difference between a class and a record.
  • Looking up how async and await fit together.
  • Reviewing core C# syntax before an interview or a new job.

Common pitfalls

  • Null reference errors. A value typed as string can be null, and calling a member on null throws at runtime. Enable nullable reference types and check for null, or use a nullable value type when a value may be missing.
  • Forgetting to await. Calling an async method without await returns a Task that may go unobserved, so exceptions get swallowed and the work may not finish. Await the Task, or store it and await it later.
  • Mutating a record you treat as a value. Records give value-based equality, but a mutable record can still change under you. Prefer the with expression to make a modified copy instead of editing in place.
  • Comparing strings by reference. Use the equality operator or the Equals method to compare string contents, since reference tricks can give surprising results. For case-insensitive checks, pass a StringComparison option.

Frequently asked questions

What is LINQ in C#?
LINQ, short for Language Integrated Query, is a set of methods and query syntax built into C# for working with collections. Instead of writing manual loops, you chain operations like Where to filter and Select to transform a sequence, and the same style works over arrays, lists, databases, and XML. LINQ queries are lazy, meaning they run only when you enumerate the result.
What is the difference between a class and a record?
Both define reference types, but a class has reference equality by default, so two objects are equal only when they are the same instance. A record adds value-based equality, so two records are equal when all their fields match, and it also generates a readable ToString and easy copying with the with keyword. Reach for a record when the type mainly carries data, and a class when it owns behavior or mutable state.
What are properties in C#?
A property looks like a field but is backed by get and set accessors, so reading or writing it can run logic such as validation. The auto-implemented form, a public property with get and set, lets the compiler create the hidden backing field for you. Properties are the standard way to expose data on a class while keeping the freedom to change how it is stored later.
What do async and await do?
Marking a method async lets you use await inside it. When you await a Task, the method pauses without blocking the thread, lets other work run, and resumes when the awaited operation finishes. This keeps apps responsive during slow work like file or network access, and it lets a server handle more requests with fewer threads.
What is a nullable type?
A nullable value type, written with a trailing question mark, can hold either a normal value or null. It is handy when a value might be missing, such as a database column with no data or an optional setting. Nullable reference types extend the same idea so the compiler can warn you about possible null usage before it turns into a runtime error.
Does this cheat sheet send my searches anywhere?
No. The entire feature list is baked into the page and all filtering happens locally in your browser with JavaScript, so nothing you type is sent to any server. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com