Comparison: C# structs vs records

structs

Strengths:

  • Performance: As value types, structs are stored on the stack (unless they are boxed or are part of a class), which can offer performance benefits for small types.
  • No Nullability: A struct cannot be null (unless it’s a nullable struct), which can prevent null reference exceptions.

Example:

public struct OrderId
{
    public int Value { get; }
    
    public OrderId(int value)
    {
        Value = value;
    }
}

Limitations:

  • Manual Implementation of Equality: By default, structs use value equality, but this is based only on their public fields. If the struct contains reference types, or if you want to compare properties, you need to manually override Equals() and GetHashCode() methods.
  • Immutability is Manual: To make a struct immutable, you have to manually ensure none of the properties can be modified after initialization, as in your example.

records

Strengths:

  • Immutability by Default: Records are immutable by default. Any attempt to change a property results in the creation of a new instance.
  • Value-Based Equality: Records provide value-based equality checks and useful ToString implementation out of the box. No need to manually override Equals() or GetHashCode().

Example:

public record OrderId(int Value);

Limitations:

  • Performance: Records are reference types and are stored on the heap, which could lead to more garbage collection than a struct, depending on how they’re used.
  • Nullability: Records can be null, which means you need to guard against null reference exceptions.