Now, for the final post in this mini-series, let's turn our attention to a feature that was originally scheduled for release in C# 10, but didn't quite make the cut: required properties.

Current Implementation

In C# 9.0 and below, there is no good way for us to tell the C# compiler that a given property of a class is required. For example, say we have a User class with the following properties.

public class User 
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public string Email { get; set; }
}

If we want to be assured that the properties DateOfBirth and Email are always defined, we must do so through careful coding. For example, we could instantiate a new User like so:

var myUser = new User()
{
    DateOfBirth = new DateTime(1984, 12, 6),
    Email = "[email protected]"
};

However, what happens if we accidentally forget to include one of those properties in an instantiation? Nothing prevents us from doing that, at the moment.

var myUser = new User()
{
    Email = "[email protected]"
}; //Where's date of birth?

New Implementation

In C# 11, we might be able to mark properties as required, using the required keyword:

public class User 
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public required DateTime DateOfBirth { get; set; }
    public required string Email { get; set; }
}
This is so new, my code highlighter package doesn't recognize the required keyword.

We can then instantiate the class like we always have:

var myUser = new User()
{
    DateOfBirth = new DateTime(1984, 12, 6),
    Email = "[email protected]"
};

Except, if we forget to include in the instantiation a property that has been marked required, the compiler will throw an error.

var myUser = new User()
{
    Email = "[email protected]"
}; //DateOfBirth missing, compiler will throw exception

Other Considerations

PLEASE NOTE: This feature is not going to make it into C# 10. From the GitHub issue tracking this:

"While I hoped to get this done for 10, that wasn't quite possible. However, this is the next feature I'm planning on working on and we're hoping to get it into preview early in C# 11."

This sucks because this would be a pretty dang neat feature. Here's hoping we see it come to fruition soon.

Happy Coding!