-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Background and Motivation
Today, the only way at runtime to determine if a generic type definition can successfully close based on a set of generic parameters is to call Type.MakeGenericType and catch any exceptions:
var genericTypeDefinition = typeof(List<>);
Type closedType = null;
try {
closedType = genericTypeDefinition.MakeGenericType(typeof(int));
} catch (ArgumentException) { }
bool canClose = closedType == null;In libraries that use open generic types heavily (such as DI containers), either the logic for determining whether or not an open generic type can be closed is duplicated, or this exception is caught. Many times, the libraries will do both - cover the basic cases but still rely on exceptions.
This is especially useful in generic constraints, where I have a collection of open generic types, and I only want to resolve the closed types that satisfy the generic constraint at runtime.
Proposed API
Expose an API to check if a given set of types can successfully satisfy the generic constraints of an open generic type:
namespace System
{
public abstract class Type
{
+ public virtual bool SatisfiesGenericConstraints(params Type[] typeArguments);
}Or can check a specific generic parameter:
namespace System
{
public abstract class Type
{
+ public virtual bool SatisfiesConstraints(Type parameter);
}Usage Examples
Simple example:
class MyType<T> where T : class
{
}typeof(MyType<>).GetGenericArguments()[0].SatisfiesConstraints(typeof(int)) // This should be false
typeof(MyType<>).SatisfiesGenericConstraints(typeof(int)) // This should be false.Risks
This API is not exposed directly in the CLR.