0

Why can't I assign List<T> to ICollection<I> where T implements interface I?

For instance:

public interface IObject {}
public class MyObject : IObject {}

public class Stuff
{
    ICollection<IObject> Objects {get;set;}
    public Stuff()
    {
        Objects = new List<MyObject>(); //<--  Cannot implicitly convert type 'ICollection<IObject>' to 'List<MyObject>'. An explicit cast exists.
    }
}

I realize the solutions to this error are as follows:

Objects = (ICollection<IObject>)new List<MyObject>();

or

Objects = new List<IObject>();

but I am just curious as to why.

itsme86
  • 19,266
  • 4
  • 41
  • 57
Price Jones
  • 1,948
  • 1
  • 24
  • 40
  • 2
    Welcome to the world of Covariance and Contravariance in Generics: http://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx – Nathan A Jul 11 '14 at 15:27
  • I'm not sure ICollection is covariant. Have you tried IEnumerable? – BradleyDotNET Jul 11 '14 at 15:28
  • 4
    Because you could then write `Objects.Add(new MyObject2())`, where `MyObject2` also implements `IObject`, and put a `MyObject2` in a list of `MyObject`. This is a violation of type safety. – Michael Liu Jul 11 '14 at 15:28
  • 3
    I swear. I see this same question at least once ever 3 days. – Euphoric Jul 11 '14 at 15:31
  • @Euphoric I figured it may have been asked before, but I couldn't get the results I was looking for when I did a search. I couldn't figure out how to word my question for the search engine. Thanks for pointing me to the answer. – Price Jones Jul 11 '14 at 15:35

0 Answers0