Skip to content

C# - Cheatsheet

This cheatsheet provides a quick reference to fundamental and modern C# concepts. C# is a versatile, cross-platform language powered by the .NET ecosystem, used for building web APIs, cloud services, desktop, mobile, and game applications. This guide will help you quickly grasp key syntax and features for development, interviews, and exams.

Modern C# (.NET 6+) uses top-level statements for console apps, simplifying the code.

// No 'using System;', 'namespace', 'class', or 'Main' method needed for simple programs.
Console.WriteLine("Hello, Modern C#!");
// This is a single-line comment.
/*
This is a
multi-line comment.
*/
/// <summary>
/// This is an XML documentation comment used for generating documentation.
/// </summary>
  • Integers: int, long, short, byte (and unsigned uint, ulong, etc.)
  • Floating-Point: double (default), float, decimal (for high-precision financial calculations)
  • Boolean: bool (true or false)
  • Character: char (a single Unicode character)
  • Structs: struct (user-defined value types)
  • Enums: enum (a set of named constants)

Reference Types (store a reference/address to the data)

Section titled “Reference Types (store a reference/address to the data)”
  • String: string (immutable sequence of characters)
  • Arrays: int[], string[], etc.
  • Classes: class (the blueprint for objects)
  • Records: record (immutable classes or structs, new in C# 9)
  • Interfaces: interface (a contract for classes)
  • Delegates: delegate (a type that represents a method signature)
// Variable declaration
string name = "Alice";
int age = 30;
// 'var' infers the type from the value
var message = "Hello, World!"; // Compiler knows 'message' is a string
// Constant declaration (value must be known at compile-time)
const double Pi = 3.14159;
int temperature = 25;
if (temperature < 0) {
Console.WriteLine("Freezing!");
} else if (temperature > 30) {
Console.WriteLine("Hot!");
} else {
Console.WriteLine("Moderate temperature.");
}
// Modern switch expression (C# 8+)
string weatherDescription = temperature switch {
< 0 => "Freezing",
> 30 => "Hot",
_ => "Moderate" // _ is the discard pattern, acts as default
};
// for loop
for (int i = 0; i < 3; i++) {
Console.WriteLine($"For loop iteration: {i}");
}
// foreach loop (for collections)
var names = new List<string> { "Ana", "Bob", "Charlie" };
foreach (var name in names) {
Console.WriteLine($"Hello, {name}!");
}
// while loop
int countdown = 3;
while (countdown > 0) {
Console.WriteLine(countdown--);
}
// do-while loop (executes at least once)
do {
// ...
} while (condition);
// Array (fixed size)
int[] numbers = { 1, 2, 3, 4, 5 };
numbers[0] = 10; // Access by index
// List (dynamic size)
using System.Collections.Generic;
var fruits = new List<string> { "Apple" };
fruits.Add("Banana");
fruits.Remove("Apple");
// Dictionary (key-value pairs)
var userAges = new Dictionary<string, int> {
{ "Alice", 30 },
{ "Bob", 25 }
};
int bobsAge = userAges["Bob"];
public int Add(int a, int b) {
return a + b;
}
// Expression-bodied method (for simple, single-line methods)
public int Multiply(int a, int b) => a * b;
public class Car {
// Properties with auto-implemented getter/setter
public string Color { get; set; }
public int Year { get; }
// Constructor
public Car(int year, string color) {
Year = year;
Color = color;
}
// Method
public void StartEngine() => Console.WriteLine("Engine started!");
}
// Creating an object (instantiation)
var myCar = new Car(2023, "Red");
myCar.StartEngine();

Records are for creating immutable data types with value-based equality.

// Positional record - concise syntax for immutable types
public record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");
var person2 = new Person("John", "Doe");
Console.WriteLine(person1 == person2); // True
// Non-destructive mutation using the 'with' expression
var person3 = person1 with { LastName = "Smith" };
Console.WriteLine(person3.LastName); // Smith
try {
int result = 10 / 0;
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: Cannot divide by zero.");
// Log the exception: Console.WriteLine(ex.Message);
} finally {
Console.WriteLine("This block always executes.");
}

For writing responsive, non-blocking asynchronous code.

public async Task<string> FetchDataAsync() {
using var client = new HttpClient();
Console.WriteLine("Starting download...");
// await pauses the method, but doesn't block the thread
string data = await client.GetStringAsync("https://api.example.com/data");
Console.WriteLine("Download complete.");
return data;
}

For querying collections in a declarative way.

using System.Linq;
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Method Syntax (most common)
var evenSquares = numbers.Where(n => n % 2 == 0)
.Select(n => n * n)
.ToList(); // [4, 16, 36, 64, 100]
// Query Syntax (SQL-like)
var oddNumbers = from n in numbers
where n % 2 != 0
select n;

14. Nullable Reference Types (NRTs, C# 8+)

Section titled “14. Nullable Reference Types (NRTs, C# 8+)”

Helps prevent NullReferenceException at compile time. Enable with <Nullable>enable</Nullable> in your .csproj file.

// With NRTs enabled:
string nonNullableName = "Valid Name";
// nonNullableName = null; // Generates a compiler warning
string? nullableName = null; // The '?' indicates this can be null
// You must check for null before using a nullable type
if (nullableName != null) {
Console.WriteLine(nullableName.Length);
}
// Or use the null-conditional operator
Console.WriteLine(nullableName?.Length);
// String Interpolation
string name = "World";
string greeting = $"Hello, {name}!";
// Common methods
string text = " Some Text ";
text.ToUpper(); // " SOME TEXT "
text.Trim(); // "Some Text"
text.Contains("Text"); // true
text.Replace("Some", "More"); // " More Text "
// Check for null or empty/whitespace
string.IsNullOrEmpty(name); // False
string.IsNullOrWhiteSpace(" "); // True
// Modern async file operations
string filePath = "myFile.txt";
// Write to a file
await File.WriteAllTextAsync(filePath, "Hello from C#!");
// Read from a file
string content = await File.ReadAllTextAsync(filePath);
// Append to a file
await File.AppendAllTextAsync(filePath, "\nThis is a new line.");