Required members
Learn mandatory properties with the required keyword.
Required members
The required keyword forces a property to be set during object creation. Declaration: public required string Name { get; set; }.
If you skip it, new Person() is a compile error; you must write new Person { Name = "Alex" }. This catches missing-data errors at compile time. required can be combined with init to get a property that is both mandatory and immutable after creation.
required + init
Combining required and init gives a property that is both mandatory and immutable: public required string Name { get; init; }.
This combination creates record-like types. The value is set with an object initializer, cannot be changed afterwards, and the code does not compile without it. It is ideal for value objects in data-carrying classes. This is the standard form for data classes in modern C#.
Exercise Add a required property to the Person class
Define a Person class. Add a public required string Name { get; set; } property. Inside Main create an instance with new Person { Name = "Alex" } and print Name.
Show example solution
Add a required Name property to Person. In Main write Person p = new Person { Name = "Alex" }; Console.WriteLine(p.Name);
Example solution:
using System;
class Person
{
public required string Name { get; set; }
}
class Program
{
static void Main()
{
Person p = new Person { Name = "Alex" };
Console.WriteLine(p.Name);
}
}
Test yourself
-
Match each keyword to its behavior
- required
- Mandatory at init
- init
- Immutable after
- set
- Writable anytime
- get
- Reading
-
Which property is mandatory to set at initialization?
- public string Name { get; set; }
- public string Name { get; init; }
- public required string Name { get; set; }
- public string Name { get; }
Show answer
public required string Name { get; set; } — Correct. With required, the property must be set at initialization.
-
Complete the required property
public ____ string Name { get; set; }Show answer
public required string Name { get; set; }