C# 11 introduced the required modifier, which indicates that the applied peroperties and fields should be initialized by all available constructors or using object initializer. We learned more about the modifier in our earlier post. In this post, we take a look into a limitation of the functionality.
Consider the following code.
publicclassFoo
{
public required string Name {get;set;}
public required Bar Bar {get;set;}
}
publicclassBar
{
publicstring Name {get;set;}
}
The required
modifier for the Foo.Name
and Foo.Bar
property indicates that these properties are required members. Notice that the Foo
class doesn’t have a constructor which is decorated with the SetsRequiredMembersAttribute
. The SetsRequiredMembersAttribute
property tells the compiler to skip the required member checks, implying the consuming code the constructor does so. This means that when initializing an instance of the Foo
class, the required fields needs to be initalized using object initializer.
Following would raise compile time errors.
// This throws compile errors.
// CS9035 Required member 'UserQuery.Foo.Name' must be set in the object initializer or attribute constructor.
// CS9035 Required member 'UserQuery.Foo.Bar' must be set in the object initializer or attribute constructor.
var foo = new Foo();
Instead, one needs to initialize the required members using object initializer.
var foo = new Foo()
{
Name = "foo",
Bar = new () { Name = "bar" }
};
So far so good !! However, note that required modifier is a compile time feature. It instructs the compiler to do additional checking to ensure required members are initialized. It also means that this is not a runtime limitation and it is possible to initialize an instance of Foo
without initializing the required members by using Activator.CreateInstance
.
var foo = (Foo)Activator.CreateInstance(typeof(Foo));
The above is perfectly valid and would create a instance of Foo
without initializing the required members. So just be aware the required modifier is limited to the compile time so that you do not fall for false impressions.
You will not always be next to me, but be sure briansclub cm hat you will have my back always.
LikeLike