views:

40

answers:

1

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?

+3  A: 

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.

Anderson Imes
Exactly what I was looking for. Another interesting thing is, if you look at that second link, it says that it's supported since .Net 2.0. I guess it's always been there since other languages have been supporting Covariance / Contravariance for a while (I think...). Never noticed that....
BFree
@BFree: interesting observation. I'll have to leave that for later to look into.
Anderson Imes