C# Interview Question #104
What is a readonly struct?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
A readonly struct is a value type whose instance fields must be readonly and whose instance state cannot be modified after construction.
Detailed Explanation
A readonly struct is a value type whose instance fields must be readonly and whose instance state cannot be modified after construction.
It communicates value semantics and can help the compiler avoid defensive copies in some scenarios. It is appropriate for small immutable values such as coordinates, measurements, identifiers, or money-like value objects.
Large structs should still be used carefully because value types are copied by value unless passed by reference.
Code Example
public readonly struct Coordinate
{
public double Latitude { get; }
public double Longitude { get; }
public Coordinate(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}
}