C# 11- Required Members

Introduction:

 In C# 9 and later we got an init keyword which defines an accessor method in a property, an init-only setter assign value to the property during object construction. This enforces immutability, so that once object is initialized, it cannot be updated again. But we have one issue because it’s not a mandatory to set a value for init property during initialization.

From the above code you can observe, we got compiler error while updating the Name property value, because we should define a value for Name property during the initialization, since it is defined as init setter. It’s bit annoying because the compiler should give an error messaging during an initialization of the object. We can overcome this issue with required keyword in C# 11.

Required Member:

Use required keyword for the class member as given below,

public class Employee
{
    public required string Name { get; init; }
}

By adding a required keyword, the default constructor requires to set a value for required member during object initialization.

Let’s define the required member during the initialization.


var employee = new Employee 
{ 
Name="Gowtham"
};

public class Employee
{
    public required string Name { get; init; }
}

Summary:

 We have seen how to use and when to use the required keyword for the class member from this blog. We will see more about C# 11 feature in my upcoming blogs.

Happy Coding 🧑‍💻

gowthamk91

Leave a Reply

%d bloggers like this: