Is there a way to achieve covariance of generic types in C# 3.5?

Posted by nullDev on Stack Overflow See other posts from Stack Overflow or by nullDev
Published on 2010-04-05T13:21:58Z Indexed on 2010/04/05 13:23 UTC
Read the original article Hit count: 275

Filed under:
|
|

This has been introduced in C# 4.0, but is there a way to achieve this in c# 3.5?

For e.g., consider the following code:

class Base
{
}

class Derived1 : Base
{
}

class Derived2 : Base
{
}

class User<T> where T : Base
{
}

class User1 : User<Derived1>
{
}

Now, I would like to have a list of User<T>, in which I can store User<Derived1> as well as User<Derived2>, but the following code fails to compile in C# 3.5:

List<User<Base>> users = new List<User<Base>>();
users.Add(new User1());

Any ideas?

© Stack Overflow or respective owner

Related posts about generics

Related posts about c#3.5