views:

32

answers:

1

Is there a way to reflect on an interface to detect variance on its generic type parameters and return types? In other words, can I use reflection to differentiate between the two interfaces:

interface IVariant<out R, in A>
{
   R DoSomething(A arg);
}


interface IInvariant<R, A>
{
   R DoSomething(A arg);
}

The IL for both looks the same.

+5  A: 

There is a GenericParameterAttributes Enumeration that you can use to determine the variance flags on a generic type.

To get the generic type, use typeof but omit the type parameters. Leave in the commas to indicate the number of parameters (code from the link):

Type theType = typeof(Test<,>);
Type[] typeParams = theType.GetGenericArguments();

You can then examine the type parameters flags:

GenericParameterAttributes gpa = typeParams[0].GenericParameterAttributes;
GenericParameterAttributes variance = gpa & GenericParameterAttributes.VarianceMask;

string varianceState;
// Select the variance flags.
if (variance == GenericParameterAttributes.None)
{
    varianceState= "No variance flag;";
}
else
{
    if ((variance & GenericParameterAttributes.Covariant) != 0)
    {
        varianceState= "Covariant;";
    }
    else
    {
        varianceState= "Contravariant;";
    }
}
Simon P Stevens
Many many thanks, Simon P Stevens.
Water Cooler v2