Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# List<Interface>: why you cannot do `List<IFoo> foo = new List<Bar>();`

Tags:

c#

generics

If you have an Interface IFoo and a class Bar : IFoo, why can you do the following:

List<IFoo> foo = new List<IFoo>();   foo.Add(new Bar()); 

But you cannot do:

List<IFoo> foo = new List<Bar>(); 
like image 228
newB Avatar asked Aug 04 '09 15:08

newB


1 Answers

At a casual glance, it appears that this should (as in beer should be free) work. However, a quick sanity check shows us why it can't. Bear in mind that the following code will not compile. It's intended to show why it isn't allowed to, even though it looks alright up until a point.

public interface IFoo { } public class Bar : IFoo { } public class Zed : IFoo { }  //.....  List<IFoo> myList = new List<Bar>(); // makes sense so far  myList.Add(new Bar()); // OK, since Bar implements IFoo myList.Add(new Zed()); // aaah! Now we see why.  //..... 

myList is a List<IFoo>, meaning it can take any instance of IFoo. However, this conflicts with the fact that it was instantiated as List<Bar>. Since having a List<IFoo> means that I could add a new instance of Zed, we can't allow that since the underlying list is actually List<Bar>, which can't accommodate a Zed.

like image 179
Adam Robinson Avatar answered Nov 01 '22 12:11

Adam Robinson