I have the following code. The two lines that create a TestClass
instance fail with the errors shown.
I would expect the first one to fail because a required property is not initialized. However, the second one calls a constructor that does initialize the required property. Why does that one fail?
And what is an attribute constructor?
void Main()
{
TestClass test1 = new(); // <== Error CS9035 Required member 'TestClass.Name' must be set in the object initializer or attribute constructor
TestClass test2 = new(""); // <== Error CS9035 Required member 'TestClass.Name' must be set in the object initializer or attribute constructor
}
class TestClass
{
public required string Name { get; set; }
public TestClass()
{
}
public TestClass(string name)
{
Name = name;
}
}
I haven't checked out this new feature too much yet but it looks like it only "plays nice" with records
and other new constructs, not ordinary classes.
Based on the docs, only the class-level primary constructor will automatically fulfill this; otherwise, your constructor has to have System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute
. Like:
class TestClass
{
public required string Name { get; set; }
public TestClass()
{
}
[System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute]
public TestClass(string name)
{
Name = name;
}
}
I thought this would work but it gives the same error:
record TestClass(string Name)
{
public required string Name { get; set; } = Name;
}
So I guess this is a partial answer.
The required modifier indicates that the field or property it's applied to must be initialized by an object initializer.
A constructor is not an "object initializer". The object initializer is the curly-braced code block that can optionally follow the instantiation of an object:
var x = new TestClass { Name = "" };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With