16 November

C# 11 – Required Members

min. read

Reading Time: 2 minutes
C# 11
C# 11

Let’s list all the features that C# 11 brings to the table. Let’s discuss them all one by one, with their use cases, and see how they can come in handy. At the bottom of each article, you can find a link to all 14 new C# features!

Required Members

In C# 9 we got init setter for properties which allowed us to force users to set the value of a class or struct via extended curtly braces syntax.

var user1 = new User(); // Valid initialization
var user2 = new User() // Valid initialization
{ 
    FullName = "Tomasz Juszczak" 
};


class User
{
    public string FullName { get; init; }
}

Both of that will work, but won’t allow for later assigning like below.

user1.FullName = "Not Tomasz Juszczak"; // Compilation error!

The problem with that is that we can define a user class without ever assigning FullName!

var user = new User(); // Compiles and work

Required keyword

Now in C# 11 we finally got required. A keyword that allows us to specify that the field is REQUIRED.

var user1 = new User(); // Not allowed now!
var user2 = new User() // Valid initialization
{ 
    FullName = "Tomasz Juszczak" 
};


class User
{
    public required string FullName { get; init; }
}

Worth mentioning is the fact that this not only works for init but for set also.

public required string Fullname { get; set; } // also valid

Further reading on dotnet GitHub pages.


Author

Tomasz Juszczak

CTO /

Technical Lead

Tomasz Juszczak

About prog

Founded in 2016 in Warsaw, Poland. Prographers mission is to help the world put the sofware to work in new ways, through the delivery of custom tailored 3D and web applications to match the needs of the customers.


Let's talk

SEND THE EMAIL