Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set SetsRequiredMembers or another attribute for only one member in C# 11?

Tags:

c#

c#-11.0

Consider the following code:

public record Foo 
{
  public required string A { get; init; }
  public required string B { get; init; }
}

public record Bar : Foo
{
   public Bar()
   {
     A = "TEST";
   }
}

var bar = new Bar
{
  B = "ANOTHER TEST"
}

In this situation the compiler will say that field A is not set, while it is clearly set it just does not know about it. Is there any workaround for this?

like image 379
Ilya Chernomordik Avatar asked Oct 18 '25 06:10

Ilya Chernomordik


1 Answers

No, at the moment there is no way to set it for a specific member. If Foo is external dependency you can workaround by adding ctor parameter for B and using SetsRequiredMembersAttribute:

public record Bar : Foo
{
   [SetsRequiredMembers]
   public Bar(string b)
   {
     A = "TEST";
     B = b;      
   }
}

var bar = new Bar("");

But use it with caution - it does not actually check if the ctor does what it claims to, i.e. adding new required member to Foo will not trigger an error.

Demo

Created an API proposal for attribute allowing to specify initialized members.

like image 155
Guru Stron Avatar answered Oct 26 '25 00:10

Guru Stron



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!