As part of ongoing efforts to ensure type safety and reduce null reference exceptions, C# 11.0 introduces the required
modifier.
This modifier can be applied to properties, fields, and parameters to indicate that they must be set by either an initializer or constructor.
Code
C#
public class NamedIdentity
{
public required string Name { get; init; }
public required Guid Identity { get; init; }
[SetsRequiredAttributes]
public NamedIdentity(string name, Guid identity)
{
Name = name;
Identity = identity;
}
// No validation needed as the compiler will check that all
// required parameter using this constructor have been set.
public NamedIdentity()
{
}
}
C#
public class NamedIdentity
{
public string Name { get; init; }
public Guid Identity { get; init; }
public NamedIdentity(string name, Guid identity)
{
Name = name;
Identity = identity;
}
// If we want to allow initializer syntax we need this constructor.
// Remember to validate all required values were set.
public NamedIdentity()
{
}
}
Notes
- You can decorate a constructor with SetsRequiredMembers to indicate to the compiler that this constructor sets all required members