I have a class with a required property. I have created a copy constructor that initializes that property to the same thing that the source instance of that class has. Why does the compiler give me the error:
CS9035: Required member 'PropertyName' must be set in the object initializer or attribute constructor.
public class Class1
{
public required string Name {get; set;}
public Class1(){}
public Class1(Class1 src)
{
Name = src.Name;
}
}
public class OtherClass
{
public void func()
{
// This works fine
var data = new Class1
{
Name = "test"
};
// This gives compiler error
var data1 = new Class1(data);
}
}
As stated in the documentation (emphasis added):
The
requiredmodifier indicates that the field or property it's applied to must be initialized by an object initializer.
The statement var data1 = new Class1(data); does not initialize the Name property using an object initializer, so you get a compiler error.
You can tell the compiler that your copy constructor initializes all required members by adding the [SetsRequiredMembers] attribute (available in the System.Diagnostics.CodeAnalysis namespace):
[SetsRequiredMembers]
public Class1(Class1 src)
{
Name = src.Name;
}
No more compiler error!
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