The code below can not compile and reports a CS9035 error. Required member 'A.FieldA' must be set in the object initializer or attribute constructor.
This seems like a false positive. The required field is set. Is there any way to work around this? I don't want the users of record B
to set the field.
public record A
{
public A(string value)
{
FieldA = value;
}
required public string FieldA { get; init; }
}
public record B() : A("field a");
public static class Test
{
public static void test()
{
var b = new B(); //Error CS9035 Required member 'A.FieldA' must be set in the object initializer or attribute constructor.
//var b = new B() { FieldA = "field a" };
}
}
Let's take a look at the documentation:
So it's only for object initializers. What you do in your constructors does not matter. But then, if you're initializing it in the constructor, you probably want a read only property, not an init only one.
If you want to do it that way, you'll have to set the
SetsRequiredMembers
attribute to your constructor, but the documentation warns against that: