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?
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: