3

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?

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • Don't use such constructors? `required` says that the *client* must initialize the field or parameter. NRTs already generated a warning/error if the parameters weren't initialized – Panagiotis Kanavos Nov 11 '22 at 09:35
  • Why not? It makes sense that I always want this field initialized, but a subclass already has done it so that we need to write a bit less code. – Ilya Chernomordik Nov 11 '22 at 09:37

3 Answers3

3

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.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

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")
{
}
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
0

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"
      };
  • This is not quite what I wanted to achieve, I still want it required, but I do want the compiler to understand that it is already set by the constructor – Ilya Chernomordik Nov 11 '22 at 10:16