C# · Lesson 2

Classes, records and structs

Classes with properties and constructors, primary constructors, records with value equality and `with`, structs vs classes, Equals/GetHashCode/ToString, immutability and encapsulation, compared with TypeScript classes and object literals.

14 min read

In short

  • Properties, not public fields: { get; private set; }
  • init and required make initializers safe
  • Records: value equality, ToString and with
  • Classes for identity, records for data, structs for small values
  • with is shallow, and lists compare by reference

Most of the code on a .NET team is types: request and response DTOs, domain entities, value objects, options classes, services. Choosing between a class, a record and a struct, and deciding what can be set from outside, is the everyday design work of C#. In TypeScript you'd often reach for a plain object literal and a type. C# has no object literals for your own types, so the type itself carries the rules: what's required, what's immutable, and what "equal" means.

Classes, fields and properties

▶ Try
var account = new Account("Ada");
account.Deposit(50m);
Console.WriteLine($"{account.Owner}: {account.Balance}");
// account.Balance = 1_000_000m;   // error CS0272: the setter is private

public class Account
{
    private readonly List<decimal> _history = new();   // a field: private state

    public Account(string owner)                       // constructor
    {
        Owner = owner;
    }

    public string Owner { get; }                       // get-only: set in the constructor only
    public decimal Balance { get; private set; }       // readable by all, writable only inside
    public int TransactionCount => _history.Count;     // computed property (no storage)

    public void Deposit(decimal amount)
    {
        if (amount <= 0) throw new ArgumentOutOfRangeException(nameof(amount));
        _history.Add(amount);
        Balance += amount;
    }
}
▶ Try
class Account {
  readonly #history: number[] = [];
  #balance = 0;
  constructor(readonly owner: string) {}
  get balance() { return this.#balance; }
  deposit(amount: number) { this.#history.push(amount); this.#balance += amount; }
}
const a = new Account('Ada');
a.deposit(50);
console.log(a.owner, a.balance);
  • A field is a variable inside the object. Fields are usually private and named _camelCase.
  • A property looks like a field from outside but is really a pair of methods (get and set). { get; set; } is an auto-property: the compiler writes the hidden field for you. Public data is always exposed as properties, never as public fields, so you can add validation later without breaking callers.
  • Members are private by default, and the .NET runtime enforces access too (only reflection gets around it). TypeScript's private only exists at compile time (its #private fields are the real thing).
  • Accessors can have their own visibility: { get; private set; } is the C# way to say "anyone can read, only I can change".

Constructors and object initializers

▶ Try
var a = new Product("SKU-1", 9.99m);                   // constructor
var b = new Product("SKU-2", 4.50m) { Tags = ["sale"] }; // constructor + object initializer
var c = new Product("SKU-3") { Price = 1m };          // chained constructor
Console.WriteLine($"{a.Sku} {b.Tags.Count} {c.Price}");

public class Product
{
    public Product(string sku, decimal price)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(sku);
        Sku = sku;
        Price = price;
    }

    public Product(string sku) : this(sku, 0m) { }      // calls the other constructor first

    public string Sku { get; }
    public decimal Price { get; set; }
    public List<string> Tags { get; set; } = [];       // property initializer: a default value
}

An object initializer (new X { A = 1 }) runs after the constructor and sets properties one by one. It's the closest thing C# has to a TypeScript object literal, and it's what ASP.NET Core, EF Core and JSON deserialization use to fill your DTOs.

init and required

Two keywords make object initializers safe:

▶ Try
var options = new StorageOptions { AccountName = "exampledata" };
Console.WriteLine($"{options.AccountName} {options.Container} {options.MaxRetries}");
// options.Container = "other";            // error CS8852: init-only property
// var bad = new StorageOptions();          // error CS9035: required member 'AccountName' must be set

public class StorageOptions
{
    public required string AccountName { get; init; }   // must be set, then never changes
    public string Container { get; init; } = "uploads";  // optional, with a default
    public int MaxRetries { get; init; } = 3;
}
  • init is a setter that only works during construction: in the constructor, in an object initializer, or in a with expression. Afterwards the property is read-only. It's TypeScript's readonly for properties you set from outside.
  • required makes the compiler insist that every new sets the property. It fixes a real problem: with nullable reference types on, a string property that nobody sets is a warning (CS8618), and required is the honest answer to "who sets this?".

Primary constructors (C# 12)

A class can take parameters right after its name. This is the usual shape of a service in a modern ASP.NET Core codebase:

▶ Try
var service = new GreetingService("Hello");
Console.WriteLine(service.Greet("Ada"));

public class GreetingService(string greeting)          // primary constructor
{
    public string Greet(string name) => $"{greeting}, {name}!";   // the parameter is in scope everywhere
}
▶ Try
class GreetingService {
  constructor(private readonly greeting: string) {} // TypeScript parameter property
  greet(name: string) { return `${this.greeting}, ${name}!`; }
}
console.log(new GreetingService('Hello').greet('Ada'));

They look like TypeScript parameter properties, but the parameters are not properties and are not readonly. They're captured into hidden fields that any method can reassign. If you want a public property, declare it: public string Greeting { get; } = greeting;. If you want a readonly field, do the same with a field: private readonly ILogger _logger = logger;. And don't do both with the same parameter: the compiler warns (CS9124) because you'd end up with two copies that can drift apart.

Records: data with value equality

A class compares by reference: two new objects are never ==, however equal their contents. That's how JavaScript objects behave too. A record compares by value:

▶ Try
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b);                 // True: same values
Console.WriteLine(ReferenceEquals(a, b));  // False: still two objects
Console.WriteLine(a);                      // Point { X = 1, Y = 2 }

var moved = a with { X = 10 };             // a copy with one property changed
Console.WriteLine($"{a} {moved}");

var (x, y) = moved;                        // deconstruction
Console.WriteLine(x + y);

var set = new HashSet<Point> { a, b, moved };
Console.WriteLine(set.Count);              // 2: a and b are the same value

public record Point(int X, int Y);
▶ Try
type Point = { readonly x: number; readonly y: number };
const a: Point = { x: 1, y: 2 };
const moved = { ...a, x: 10 };                 // spread is TypeScript's `with`
console.log(a === { x: 1, y: 2 } as Point);    // false: JS objects compare by reference
console.log(JSON.stringify(moved));

From one line, record Point(int X, int Y) gives you:

  • A constructor and init-only properties X and Y (immutable after construction).
  • Value equality: Equals, ==, != and a matching GetHashCode, so records work as dictionary keys and in sets.
  • A readable ToString: Point { X = 1, Y = 2 }. Great in logs and test failures.
  • with expressions for non-destructive changes, like { ...obj, x: 10 }.
  • Deconstruction: var (x, y) = point;.

You can add members to a record like any class: methods, computed properties, extra properties, static factory methods, even your own constructor validation.

▶ Try
var line = new OrderLine("SKU-1", 2.50m, 4);
Console.WriteLine(line.Total);
Console.WriteLine(line with { Quantity = 1 });

public record OrderLine(string Sku, decimal UnitPrice, int Quantity)
{
    public decimal Total => UnitPrice * Quantity;   // computed: not part of equality, but ToString shows it
}

The generated ToString prints every public property, computed ones included, while equality only compares the stored values.

Records are the natural fit for DTOs (API requests and responses, messages on a message queue), value objects (Money, EmailAddress, DateRange) and events. Entities with an identity and a lifecycle (a Customer you load, change and save with EF Core) are usually classes.

Three record traps

▶ Try
var a = new Order("A-1", ["book"]);
var b = a with { };                    // a shallow copy: same list object
b.Items.Add("pen");
Console.WriteLine(a.Items.Count);      // 2: a changed too
Console.WriteLine(a == new Order("A-1", ["book", "pen"]));  // False: the List is compared by reference
Console.WriteLine(a);                  // Items = System.Collections.Generic.List`1[System.String]

public record Order(string Id, List<string> Items);
  1. with is shallow. It copies property values, and for a list that value is a reference.
  2. Equality is only as deep as each property's own Equals. List<T> and arrays compare by reference, so a record containing one isn't a value anymore. Use immutable collections and write your own Equals/GetHashCode (the "Records with collections" exercise), or keep collections out of value objects.
  3. ToString prints each property's ToString, which for a list is its type name.

Structs: value types you define

A struct is a value type: assigning it copies the whole thing. int, decimal, DateTime, Guid and TimeSpan are all structs.

▶ Try
var p1 = new PointStruct { X = 1 };
var p2 = p1;          // a copy
p2.X = 5;

var c1 = new PointClass { X = 1 };
var c2 = c1;          // a second reference to the same object
c2.X = 5;

Console.WriteLine($"{p1.X} {c1.X}");   // 1 5

public struct PointStruct { public int X { get; set; } }
public class PointClass { public int X { get; set; } }

When to choose a struct:

  • It's small (a few fields, up to about 16 bytes is the usual guideline), it represents a single value, and it's immutable. Think coordinates, money amounts, ids, ranges.
  • You create huge numbers of them and want to avoid heap allocations (game loops, parsers, high-throughput services).

Otherwise, use a class or a record. When you do write a struct, make it readonly so nobody can mutate a copy by accident, and prefer readonly record struct to get value equality and ToString generated:

▶ Try
var id = new CustomerId(42);
Console.WriteLine(id);                      // CustomerId { Value = 42 }
Console.WriteLine(id == new CustomerId(42)); // True
Console.WriteLine(default(CustomerId));     // CustomerId { Value = 0 }: structs always have a default

public readonly record struct CustomerId(int Value);

Mutable structs are a classic source of bugs, because you so easily change a copy:

▶ Try
var list = new List<Counter> { new Counter() };
list[0].Increment();          // the indexer returns a COPY; the copy is incremented and thrown away
var array = new[] { new Counter() };
array[0].Increment();         // array elements are accessed in place
Console.WriteLine($"{list[0].Value} {array[0].Value}");   // 0 1

public struct Counter
{
    public int Value { get; private set; }
    public void Increment() => Value++;
}

Strongly typed ids (CustomerId, OrderId) as readonly record struct are a popular pattern: they cost nothing at runtime, and the compiler stops you passing an OrderId where a CustomerId belongs. In TypeScript you'd need a branded type for that.

Equals, GetHashCode and ToString

Every .NET type inherits three methods from object. Records and record structs generate good versions; for a class you write them yourself when you want value semantics.

▶ Try
var a = new Sku("abc-1");
var b = new Sku("ABC-1");
Console.WriteLine(a.Equals(b));       // True: our rule ignores case
Console.WriteLine(a == b);            // True: we overloaded == too
Console.WriteLine(a.GetHashCode() == b.GetHashCode());
Console.WriteLine(a);                 // ABC-1

public sealed class Sku : IEquatable<Sku>
{
    public Sku(string code) => Code = code.ToUpperInvariant();
    public string Code { get; }

    public bool Equals(Sku? other) => other is not null && Code == other.Code;
    public override bool Equals(object? obj) => Equals(obj as Sku);
    public override int GetHashCode() => Code.GetHashCode();
    public override string ToString() => Code;

    public static bool operator ==(Sku? left, Sku? right) => Equals(left, right);
    public static bool operator !=(Sku? left, Sku? right) => !Equals(left, right);
}

The rules that matter:

  • Override Equals and GetHashCode together. Dictionary, HashSet and LINQ's Distinct first compare hash codes, then call Equals. Equal objects must have equal hash codes, or lookups fail.
  • Hash what you compare. Use HashCode.Combine(a, b, c) for several fields. Don't include fields that aren't part of equality.
  • Keys must not change. If a property used in GetHashCode changes while the object is in a HashSet or used as a Dictionary key, the collection can no longer find it. Immutable types avoid this.
  • == on a class is reference equality unless you overload the operator. Records overload it for you.
  • ToString is what logs, the debugger and string interpolation show. Override it on anything you'll log.

Immutability and encapsulation

Immutable objects can't be put into a bad state after construction, can be shared freely between threads and are safe as dictionary keys. Modern C# makes them cheap: init, records, with, readonly struct, and System.Collections.Immutable (ImmutableList<T>, ImmutableDictionary<TKey, TValue>).

When a class does own mutable state, encapsulate it: keep the field private, change it only through methods that enforce the rules, and hand out read-only views.

▶ Try
var team = new Team("Platform");
team.Add("ada");
team.Add("Ada");                       // ignored: already a member

if (team.Members is List<string> list) list.Add("mallory");   // can a caller sneak in?
Console.WriteLine(string.Join(", ", team.Members));

public class Team(string name)
{
    private readonly List<string> _members = [];

    public string Name { get; } = name;
    public IReadOnlyList<string> Members => _members.AsReadOnly();   // a read-only view, not the list

    public void Add(string member)
    {
        if (_members.Contains(member, StringComparer.OrdinalIgnoreCase)) return;
        _members.Add(member);
    }
}

Returning _members typed as IReadOnlyList<string> is not enough: the caller can cast it back to List<string> and change your state. AsReadOnly() returns a wrapper whose Add throws, and ToList() or ToArray() returns a copy. The interface type documents the intent; the wrapper enforces it.

Inheritance, briefly

▶ Try
Shape[] shapes = [new Circle(1), new Square(2)];
foreach (var s in shapes) Console.WriteLine($"{s.Name}: {s.Area():F2}");

public abstract class Shape
{
    public abstract double Area();                   // must be overridden
    public virtual string Name => GetType().Name;    // may be overridden
}

public sealed class Circle(double radius) : Shape
{
    public override double Area() => Math.PI * radius * radius;
}

public sealed class Square(double side) : Shape
{
    public override double Area() => side * side;
    public override string Name => "Square (4 sides)";
}
  • Methods are not virtual by default. A base class opts in with virtual or abstract, and a subclass says override. This is stricter than TypeScript, where every method can be overridden.
  • sealed stops further inheritance. Many teams seal classes by default and use interfaces (the Generics & interfaces topic) for polymorphism.
  • Records can inherit from records. Equality then also checks the runtime type, so a Person is never equal to an Employee with the same name.

Common mistakes

  • Public setters everywhere. { get; set; } on every property makes every invariant optional. Start with { get; } or { get; init; } and loosen only when needed.
  • Collections in records. record Order(List<Line> Lines) has reference equality on Lines and a shallow with. An immutable collection (ImmutableArray<T>, or a copy behind IReadOnlyList<T>) makes sharing safe, but it still compares by reference, so add custom equality when the record must compare by value.
  • Treating primary constructor parameters as readonly fields. They can be reassigned. Copy them into readonly fields or properties when it matters.
  • Mutable structs. Changing a copy instead of the original. Make structs readonly.
  • Equals without GetHashCode. The compiler warns (CS0659), and dictionary lookups break.
  • Mutating a dictionary key. Keys must be immutable, or at least must not change while in the collection.
  • Leaking internal lists. Return AsReadOnly() or a copy, not the field.

In a real codebase

Side note
// An ASP.NET Core API (not runnable here)
public record CreateOrderRequest(string CustomerId, IReadOnlyList<OrderLineDto> Lines);
public record OrderLineDto(string Sku, int Quantity);
public record OrderCreated(Guid OrderId, DateTimeOffset At);   // an event for the message broker

public sealed class OrderService(IOrderRepository repository, TimeProvider clock, ILogger<OrderService> logger)
{
    public async Task<OrderCreated> CreateAsync(CreateOrderRequest request, CancellationToken ct)
    {
        var order = Order.Create(request.CustomerId, request.Lines.Select(l => (l.Sku, l.Quantity)));
        await repository.AddAsync(order, ct);
        logger.LogInformation("Created order {OrderId} for {CustomerId}", order.Id, request.CustomerId);
        return new OrderCreated(order.Id, clock.GetUtcNow());
    }
}

public class StorageOptions          // bound from appsettings.json with the options pattern
{
    public required string AccountName { get; init; }
    public string Container { get; init; } = "uploads";
}

Records for the data that crosses boundaries, a class with a primary constructor for the service (its dependencies arrive through dependency injection), and an options class with required and init. That mix is what you'll see in most modern .NET codebases.

The exercises

  1. A bank account: a class that protects its own balance with private setters and guard clauses.
  2. Money as a record: value equality, with, an operator and a custom ToString.
  3. A shopping cart: encapsulated state, immutable lines updated with with, and read-only views.
  4. An email address value object: private constructor, Parse/TryParse, normalization and equality.
  5. Records with collections: write Equals and GetHashCode that compare lists and sets by value.
  6. Undo and redo: immutable snapshots, a bounded history and coalesced edits.

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 10-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app