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

Time:11-11

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?

CodePudding user response:

Not directly an answer, but a workaround that seems to work fine:

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

public record Bar : Foo("TEST")
{
}

CodePudding user response:

Sure you can set required only one member if needed.

public record Foo
{
    public 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"
      };

CodePudding user response:

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

  • Related