Prior to C# 11 struct constructors were required to explicitly assign every field and auto-property. This was tedious when only some fields needed non-default values and the rest could remain at their defaults.
C# 11 removes this requirement by having the compiler automatically initialize any fields not explicitly assigned by the constructor to their default values.
This matters most for structs with a mix of required and optional state. A struct with ten fields that only need two of them set in a given constructor previously required eight lines of = default; noise, which obscured which values the constructor actually cared about.
Code
csharp
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public bool IsValid { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
// IsValid is automatically initialized to default (false)
}
}csharp
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public bool IsValid { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
IsValid = default; // Required or the compiler would error
}
}Notes
- All unassigned fields are set to
defaultat the start of the constructor, before its body runs, so the values are available immediately - The workaround before C# 11 was
this = default;as the first statement of the constructor - It removes the need to assign but does not change what
defaultmeans:new Point[10]anddefault(Point)still produce the all-zero struct without running a constructor - A
readonlyfield can be left unassigned and keeps its default value, which was the most common source of "field must be fully assigned" errors - See Parameterless struct constructors C# 10.0 for the explicit parameterless constructor that made this implicit defaulting rule necessary.