1

I have an interface:

interface IFoo<out T> 
{
   T Get();
}

and some instances like IFoo<int> a, IFoo<User> u, IFoo<string> s and etc. There is a List<IFoo<object>> used to collect them. But variance doesn't work for value types, is there a proper way to put them in the list?

Community
  • 1
  • 1
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • 2
    What is `out T` when used as a type parameter? –  Oct 10 '11 at 05:44
  • 3
    @pst - [Covariance and Contravariance](http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx) – Kobi Oct 10 '11 at 05:46

1 Answers1

3

It doesn't look like you need generics for this list, so you can have the interface implement a non-generic interface:

interface IFoo<out T> : IFoo { }

That way, all of your objects implement the same interface. This may not be a bad idea, since they do have something in common. Now you can simply use a List<IFoo>.

Kobi
  • 135,331
  • 41
  • 252
  • 292