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>();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
myListis aList<IFoo>, meaning it can take any instance ofIFoo. However, this conflicts with the fact that it was instantiated asList<Bar>. Since having aList<IFoo>means that I could add a new instance ofZed, we can’t allow that since the underlying list is actuallyList<Bar>, which can’t accommodate aZed.