Sebastian Gregor Sebastian Gregor - 3 months ago 9
C# Question

Reflection over Type Constraints

In class and method definitions, it's possible to add type constraints like

where T : IFoo
.

Is it possible to reflect over those constraints with
System.Type
or
MethodInfo
? I haven't found anything so far; any help will be appreciated.

Answer

You can iterate through the generic parameters to the type, and for each parameter, you can ask for the constraint types.

You do this using:

Take a look at this code, which you can run through LINQPad:

void Main()
{
    Type type = typeof(TestClass<>);
    foreach (var parm in type.GetGenericArguments())
    {
        Debug.WriteLine(parm.Name);
        parm.GetGenericParameterConstraints().Dump();
    }
}

public class TestClass<T>
    where T : Stream
{
}

The output is:

T

Type [] (1 item)  
typeof (Stream)

To find other constraints, such as new(), you can use the .GenericParameterAttributes flags enum, example:

void Main()
{
    Type type = typeof(TestClass<>);
    foreach (var parm in type.GetGenericArguments())
    {
        Debug.WriteLine(parm.Name);
        parm.GetGenericParameterConstraints().Dump();
        parm.GenericParameterAttributes.Dump();
    }
}

public class TestClass<T>
    where T : new()
{
}

Which outputs:

T

Type [] (1 item)  
typeof (Stream)

DefaultConstructorConstraint
Comments