Search code examples
c#required-field

C# 11 required member false positive


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" };
    }
}

Solution

  • Let's take a look at the documentation:

    The required modifier indicates that the field or property it's applied to must be initialized by an object initializer.

    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:

    The SetsRequiredMembers disables the compiler's checks that all required members are initialized when an object is created. Use it with caution.