Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine the Variance of an Interface / Delegate in C# 4.0?

So now that we have generic Covariance and Contravariance on interfaces and delegates in C#, I was just curious if given a Type, you can figure out the covariance/contravariance of its generic arguments. I started trying to write my own implementation, which would look through all of the methods on a given type and see if the return types and or arguments match the types in the generic arguments. The problem is that even if I have this:

public interface IFoo<T>
{
   void DoSomething(T item);
}

using my logic, it LOOKS like it should be contravariant, but since we didn't actually specify:

public interface IFoo<in T>
{
   void DoSomething(T item);
}

(the in parameter) it isn't actually contravariant. Which leads to my question: Is there a way to determine the variance of generic parameters?

like image 505
BFree Avatar asked May 27 '10 04:05

BFree


1 Answers

I don't know why you would want this, BUT you can look at it with reflection from outside of the type. Here's information on looking at Generic Parameters for a type using reflection:

http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx

Specifically, the property Type.GenericParameterAttributes on the type you get back from a call to Type.GetGenericParameters will reveal the Co/Contravariance properties of the generic argument... it's a bitwise enum that will reveal the combination of this information:

http://msdn.microsoft.com/en-us/library/system.reflection.genericparameterattributes.aspx

Really interesting... thanks for asking this and making me look it up.

like image 194
Anderson Imes Avatar answered Oct 13 '22 21:10

Anderson Imes