Unlike classes, structs are by default copied instead of referenced. Typically, you use structs to design small data-centric types that provide little or no behavior. For example datetime is implemented as a struct: https://learn.microsoft.com/en-us/dotnet/api/system.datetime
public struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}
public double X { get; }
public double Y { get; }
public override string ToString() => $"({X}, {Y})";
}
readonly
Because structure types have value semantics, it's common to define immutable
structure types. This can be done with the readonly modifier.
public readonly struct Coords
{
public Coords(double x, double y)
{
X = x;
Y = y;
}
public double X { get; init; }
public double Y { get; init; }
public override string ToString() => $"({X}, {Y})";
}
usage
var location = new Coords(2, 4);
Console.WriteLine($"location.X, location.Y");
Because a struct is a value type rather than a reference type you cannot have a
null struct. Each field will use it's zero value, which would be null for
any reference fields.