How can I put subclasses from one base layer into a list?

How can I put subclasses from one base class into a list?

I am working with ASP.NET MVC3 and created a basemodel class with properties like name, age, etc. Now I have created submodels (subclasses) with more details. To handle subclasses easily I need a list with objects in it, but how?

I've read about interfaces or ICollection and so on, but don't know which is the right choice and how to start :-(

+2


source to share


2 answers


Just create the list so that the base class:

List<BaseClass> myList = new List<BaseClass>();

      

then add subclass objects as usual:

myList.Add(new SubClass1());
myList.Add(new SubClass2());

      



etc .. where:

public class SubClass1 : BaseClass {}
public class SubClass2 : BaseClass {}

      

Then, when you get them, you can use the is

and operators as

to determine what type they really are and deal with them as needed.

+3


source


I would recommend

List<BaseClass>

      



for

class Derived1 : BaesClass {}
class Derived2 : BaesClass {}

      

+1


source







All Articles