Proposal: Introduce new<BaseType> Constraint #9067
Unanswered
NigelBess
asked this question in
Language Ideas
Replies: 1 comment 2 replies
-
What benefits does this provide over the existing |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Summary
Introduce a new generic constraint for C#, tentatively called
new<BaseType>
, that ensures a typeT
can be constructed in the same way asBaseType
—including matching constructor signatures and satisfying all required members.Motivation
Required Members
In C# 11, required members can make the existing new() constraint insufficient if a subclass has extra required members or a constructor signature that deviates from its base.
Generic Reusability
Generic methods often need to “new up” objects that precisely conform to a base type’s construction pattern, ensuring consistency and avoiding runtime exceptions.
Better Static Guarantees
Without such a constraint, developers must fall back on factory delegates or reflection—both less direct and more prone to errors. A stronger constraint provides clearer intent at compile time.
Detailed Design
New Constraint Form
where T : new<BaseType>
Compiler Enforcement
T
must expose at least the same public constructors asBaseType
(including a parameterless one, ifBaseType
has it).T
may not introduce additional required members.Compile‐time Errors
Any mismatch in required members or constructor signatures causes a compile‐time error when applying new.
Example In a Real World Use-Case
Drawbacks
Additional Concerns
Alternatives
Automatic Enforcement: Simply enforce the initialization of required properties when where T : BaseType, new() is used. However, this might require deeper compiler changes or could silently break existing code.
Conclusion
A new constraint would offer compile‐time guarantees that a generic type parameter can be constructed exactly like its base type, particularly for required members. This addition aligns with C#’s expanding use of required members, providing safer, more expressive generics and addressing the widespread issue of ensuring correct subclass initialization.
Beta Was this translation helpful? Give feedback.
All reactions