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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With