Looking at the example in the reference you linked:
Microsoft Learn: required modifier (C# Reference)
I'm going to focus on the Person
class:
public class Person
{
public Person() { }
[SetsRequiredMembers]
public Person(string firstName, string lastName) =>
(FirstName, LastName) = (firstName, lastName);
public required string FirstName { get; init; }
public required string LastName { get; init; }
public int? Age { get; set; }
}
If I had properties that were required, I would only expose the constructor with the parameters you need:
public class Person
{
//public Person() { }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
}
Alternatively, you could make the constructor private and use a factory approach:
public class Person
{
private Person() { }
public static Person CreatePerson(string firstName, string lastName)
{
var person = new Person()
{
FirstName = firstName,
LastName = lastName
};
return person;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
}