Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required keyword causes error even if member initialized in constructor

Tags:

c#

.net-core

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;
    }
}
like image 799
Jonathan Wood Avatar asked Sep 13 '25 16:09

Jonathan Wood


2 Answers

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.

like image 118
Joe Sewell Avatar answered Sep 16 '25 07:09

Joe Sewell


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 = "" };
like image 34
Moho Avatar answered Sep 16 '25 05:09

Moho