Expand where T : new()
constructor constraint to allow known parameter types
#8542
-
I don't see any reason this couldn't be done. The compiler will be able to look at the public constructors of a type and know if those are available. This can be useful when wanting to instantiate generic unknown types but with well-known parameters. A good example of this could be custom exceptions that follow the standard exception constructor patterns. Syntax:
E.g.
Use case example: public class GenericFailureHandler<TExceptionType>
where TExceptionType : Exception
where TExceptionType : new(string)
where TExceptionType : new(string, Exception)
{
public void Handle(Exception parentException)
{
...
throw new TExceptionType("My reason", parentException);
}
} If This can avoid the This also means it would help with Native AOT if the compiler knows about the constructor usage at compile time. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Logically, yes, this makes sense. But the IL does not support it. Generic constrains must be one or more of the following:
See II.10.1.7 in ECMA-335 (6th edition) |
Beta Was this translation helpful? Give feedback.
#769, #1330, #1574, #1626, #1633, #4532