newbie question: generic collections cast

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm passing instance of List<DrawNode> to my method
AddRange(IEnumerable<DrawObject> objects)
But I got this error:

Argument '1': cannot convert from
'System.Collections.Generic.List<MyNamespace.DrawNode>' to
'System.Collections.Generic.IEnumerable<MyNamespace.DrawObject>'

I don't understand why does compiler complain, when List<> has IEnumerable<>
interface and DrawNode is inherited from DrawObject,

so both are just general types. So shouldn't they accept specific inherited
types without explicit cast?

Thank you for answer in advance.
 
carry,

No, it should not. The reason is that if you were able to convert the
list to a List<DrawObject> then you could theoretically add DrawObject2
instances to List<DrawNode>, which would end up causing a problem.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top