C# Cheatsheet
Object Modeling
Use this C# reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Classes and Properties
public class BankAccount { public string Owner { get; } public decimal Balance { get; private set; } public BankAccount(string owner, decimal openingBalance) { Owner = owner; Balance = openingBalance; } public void Deposit(decimal amount) { Balance += amount; } }
Properties expose state. Private setters let the class control changes.
Primary Constructors, required, and init
// Primary constructor (C# 12): parameters are in scope in the whole body public class Counter(int start) { public int Value { get; private set; } = start; public void Increment() => Value++; } public class UserDto { public required string Email { get; init; } // must be set at creation public string? DisplayName { get; init; } // settable only in the initializer } var dto = new UserDto { Email = "ada@example.com" }; // dto.Email = "new"; // error CS8852: init-only property
required + init gives constructor-like guarantees with object-initializer syntax, the standard shape for DTOs and options classes.
Constructors and this
public class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { this.X = x; this.Y = y; } }
this refers to the current object. It is optional when names do not conflict, but useful for clarity.
Records
public record User(int Id, string Name); var a = new User(1, "Ada"); var b = a with { Name = "Ada Lovelace" }; public readonly record struct Point3(double X, double Y, double Z); // value-type record
Records are concise data models with value-based equality, a readable ToString, and nondestructive mutation through with.
Structs and Enums
public readonly struct Money { public decimal Amount { get; } public Money(decimal amount) => Amount = amount; } enum Status { Draft, Published, Archived }
Use structs for small immutable values. Use enums for a known finite set of named choices.
Interfaces and Inheritance
public interface IShape { double Area(); } public class Circle : IShape { public double Radius { get; } public Circle(double radius) => Radius = radius; public double Area() => Math.PI * Radius * Radius; }
Prefer interfaces for capabilities and contracts. Use inheritance sparingly for true is-a relationships.