Add Type Constraint for Parameterless Constructor that allows required
Members
#9222
Unanswered
AeonSake
asked this question in
Language Ideas
Replies: 2 comments 1 reply
-
What if you have: public class B : A
{
public required string OtherProp { get; init; }
}
var b = CreateInstance<B>(10); // no CS9040
Assert.AreEqual(null, b.OtherProp); // OOPSIES!!! |
Beta Was this translation helpful? Give feedback.
1 reply
-
Thinking about this a bit more, I don't think a new modifier/keyword is even needed here. This can work if the compiler ensures that class |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
There is currently no way to use the constraint of a parameterless constructor on a type that also has
required
members. This can be especially annoying for factory methods or lambda builders.Example:
Even though the requirements of the base class
A
have been satisfied (allrequired
members are set), the call to the method itself fails because the use ofB
is not allowed in this context because it has required members.It would be great to have a constraint for this scenario as I feel like this is missing from the introduction of the
required
modifier. A specification proposal could look like this (following the recent addition ofallows ref struct
):The compiler in this case would need to verify that all required members of the constrained type have been satisfied and that inherited types don't add additional required members.
Beta Was this translation helpful? Give feedback.
All reactions