Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 306
Sebastian Gregor Avatar asked Mar 25 '11 13:03

Sebastian Gregor


3 Answers

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:

  • Type.GetGenericArguments of Type to find the generic arguments to the type, ie. Type<T>, you would find T.
  • Type.GetGenericParameterConstraints gives you the base types that each such parameter is constrained against, you call this on the arguments you find from the above method.

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
like image 178
Lasse V. Karlsen Avatar answered Oct 21 '22 02:10

Lasse V. Karlsen


You can use the GetGenericParameterConstraints() method to do that.

like image 34
Frédéric Hamidi Avatar answered Oct 21 '22 02:10

Frédéric Hamidi


Using a previously found System.Type you can use GetGenericParameterConstraints().

Here's an excellent MSDN article on Generics and Reflection.

like image 41
Joshua Rodgers Avatar answered Oct 21 '22 03:10

Joshua Rodgers