inserting instances of subclass into a generic List

  • Thread starter Thread starter puzzlecracker
  • Start date Start date
P

puzzlecracker

A quick knowledge based question who knows of top of his head.


public class Base
{


}

public class Derived: Base

List<Base> list=new List<Base>();

list.Add(new Base());
list.Add(new Derived());
......etc


Issues here?
 
puzzlecracker said:
A quick knowledge based question who knows of top of his head.


public class Base
{


}

public class Derived: Base

List<Base> list=new List<Base>();

list.Add(new Base());
list.Add(new Derived());
.....etc


Issues here?
None whatsoever, if you fix the obvious syntax error. Every Derived is also
a Base, so any container of Base references will also accept Derived references.

You may be thinking of the classic problem scenario of why a List<Derived>
is not a List<Base>; that's a different can of worms. The MSDN actually has
a topic devoted to it: http://msdn.microsoft.com/library/ms228359

C# 4.0 will bring changes in this regard too, see
http://code.msdn.microsoft.com/csharpfuture .
 
A quick knowledge based question who knows of top of his head.

public class  Base
{

}

public class Derived: Base

List<Base> list=new List<Base>();

list.Add(new Base());
list.Add(new Derived());
.....etc

Issues here?

Did you try it?
 
Back
Top