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

Posted by BFree on Stack Overflow See other posts from Stack Overflow or by BFree
Published on 2010-05-27T04:19:23Z Indexed on 2010/05/27 4:21 UTC
Read the original article Hit count: 251

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection