C# - Required Members
-
Allows you to specify that a property or field of a class/struct/record must be set in an object initializer.
-
public class Vehicle { public required string Name {get; init;} public required bool IsTaxed {get; init;} } var m = new Vehicle() { (1) Name = "Test" };
1 Fails to compile unless all required properties are set in the initializer. -
Useful when you have properties that are non-optional.
-
Do not need to enforce required values using the constructor.
-
Much more cleaner syntax.
-
You can also create an optional constructor that can set the required values.
public class Vehicle { public required string Name {get; init;} public required bool IsTaxed {get; init;} public Vehicle () { (1) } [SetsRequiredMembers] (2) public Vehicle (string name) { Name = name; isTaxed = false; } }
1 The default constructor is still available. 2 This is a new helper ctor that sets all the properties. -
Try not to use the above pattern.
-
As it is possible to add a new required field at a later date and forget to update the constructor.
-
The code crashes at runtime with a
NullReferenceException
.
-