1

I have generic container class I'm using that I'm trying to write a OfType routine for. However the types I'm passing in are also generics. Here's an example:

Entities.OfType<Foo<Bar>>()

and my function definition:

public IEnumerable T OfType<T>()
{
    foreach (var e in Values)
        if (e is T)
            yield return (T)e;
}

If Entities are defined as a collection of Foo<Base> I get an error Foo<Bar> does not inherit from Foo<Base>. However Bar does inherit from Base.

Is there a way around this limitation?

Timothy Baldridge
  • 10,455
  • 1
  • 44
  • 80

2 Answers2

2

Note that even though Bar inherits from Base - Foo<Bar> and Foo<Base> are two completely different generic types not related through inheritance.

Bar and Base in this case are type parameters and C#4.0 supports covariance/contravariance for generic interfaces which may help you to solve the problem.

Your code will work in C#4.0 if Foo is an interface declared as following:

interface IFoo<in T> { /* methods, etc. */ }

Note that no method in IFoo may return T.

You'll be able to assign IFoo<Base> object to a variable of type IFoo<Bar> where Bar inherits from Base. This is an example of contravariance.

AlexD
  • 5,011
  • 2
  • 23
  • 34
0

C# Generics are not covariant. A Foo<Bar> is not assignment-compatible with Foo<Base>

thecoop
  • 45,220
  • 19
  • 132
  • 189