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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With