The required
modifier forces you to set a property or a filed to a value when you instantiate.
public class Movie
{
public required string Name { get; set; }
public required string Genre { get; set; }
public decimal Gross { get; set; }
}
When you attempt to instantiate a Movie without setting the Name
and Genre
, you will see a compiler error, as shown below:
Required member 'Movie.Name' must be set in the object initializer or attribute constructor. [RequiredModifier]
Required member 'Movie.Genre' must be set in the object initializer or attribute constructor. [RequiredModifier]
As the error says, we have two options to overcome the error.
- Set their value in the object initializer:
Movie lordOfWar = new()
{
Name = "Lord of War",
Genre = "Drama",
Gross = 72617068M
};
Console.WriteLine("{0} is a {1} film. It was grossed {2:C}",
lordOfWar.Name, lordOfWar.Genre, lordOfWar.Gross);
- When you try to set required properties and fields in a constructor, you will still encounter the error. To handle that error, you can import the namespace and then decorate the constructor with the attribute that informs the compiler that all required properties and fields are being set, as shown in the following code:
using System.Diagnostics.CodeAnalysis; // [SetsRequiredMembers]
public class Movie
{
public required string Name { get; set; }
public required string Genre { get; set; }
public decimal Gross { get; set; }
[SetsRequiredMembers]
public Movie(string name, string genre)
{
Name = name;
Genre = genre;
}
}
In the Program.cs:
Movie lordOfWar = new(name: "Lord Of War", genre: "drama")
{
Gross = 72617068
};
Console.WriteLine("{0} is a {1} film. It was grossed {2:C}.",
lordOfWar.Name, lordOfWar.Genre, lordOfWar.Gross);
Further information:
Required members
Required modifier