Praveen
Praveen

Reputation: 304

Assign Derived Class Collection to Base Class Collection compilation error

I have two classes

class Base
{

}
class Derived : Base
{

}

Base base = new Derived(); no compilation error

if I do ICollection<Base> collBase = new List<Derived>(); it gives the compilation error. Is there any other alternatives to solve this?

Upvotes: 1

Views: 1084

Answers (1)

asawyer
asawyer

Reputation: 17808

If you are using .Net version 4 : Change ICollection to IEnumerable

http://msdn.microsoft.com/en-us/library/dd799517.aspx

Edit - more useful reading

http://blogs.msdn.com/b/ericlippert/archive/2007/10/26/covariance-and-contravariance-in-c-part-five-interface-variance.aspx

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/default.aspx

attempting to clarify further why you can't do this:

class animal {}
class dog : animal {}
class cat : animal {}

ICollection<animal> dogs = new List<dog>(); //error (Or List<T>, same error) because...
dogs.Add(new cat()); //you just dogged a cat

IEnumerable<animal> dogs = new List<dog>(); // this is ok!

Upvotes: 4

Related Questions