Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Constructor does not satisfy `required` property

Tags:

c#

c#-11.0

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);
  }
}
like image 559
Matt Zappitello Avatar asked Feb 27 '26 13:02

Matt Zappitello


1 Answers

As stated in the documentation (emphasis added):

The required modifier 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!

like image 71
Michael Liu Avatar answered Mar 01 '26 03:03

Michael Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!