Skip to content

Type.SatisfiesGenericConstraints proposal #28033

@jbogard

Description

@jbogard

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-System.ReflectionenhancementProduct code improvement that does NOT require public API changes/additionsneeds-further-triageIssue has been initially triaged, but needs deeper consideration or reconsideration

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions