16 November

C# 11 – Required Members

Programming

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.


Let's talk

SEND THE EMAIL

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.

I agree that my data in this form will be sent to [email protected] and will be read by human beings. We will answer you as soon as possible. If you sent this form by mistake or want to remove your data, you can let us know by sending an email to [email protected]. We will never send you any spam or share your data with third parties.