Skip to content

readonly struct

Context: readonly struct indicates that the struct is immutable. All instance fields must be readonly, and the compiler enforces immutability.

public readonly struct Vector
{
public double X { get; }
public double Y { get; }
public Vector(double x, double y) => (X, Y) = (x, y);
public double Length => Math.Sqrt(X * X + Y * Y);
}
  • Clear intent: this struct cannot be modified after creation
  • Performance: compiler can avoid defensive copies
  • Thread‑safe by design

Even if the struct is not readonly, you can mark individual methods as readonly to prevent modification.

public struct Point
{
public int X, Y;
public readonly double DistanceFromOrigin() => Math.Sqrt(X * X + Y * Y);
}

Immutable settings: Use readonly struct for configuration values that never change (e.g., AppConstants with double Pi, int MaxRetries).

Example: In System.Text.Json, serialization options can be readonly structs for performance.