I have an inheritance tree like so:
BaseType
TypeA : BaseType
TypeB : BaseType
TypeC : BaseType
Each derived object has a variable named objectName that defines that object's name.
I also have an array and a list that both hold theBaseType objects as well as any objects derived from BaseType. The array has objects stored in it upon being created, meanwhile the list is empty for future use:
BaseType[] arrayA = new BaseType[] { new TypeA(), new TypeB(), new TypeC(), }
List<BaseType> listA = new List<BaseType>;
I also have a method that is used to add an object that is in the array to the list:
public void AddToList(BaseType itemToAdd)
{
if(itemToAdd.objectName == "Type A")
{
listA.Add(new TypeA());
}
else if(itemToAdd.objectName == "Type B")
{
listA.Add(new TypeB());
}
else if(itemToAdd.objectName == "Type C")
{
listA.Add(new TypeA());
}
}
How can I avoid having to use all of those if commands? At one point I tried:
public void AddToList(BaseType itemToAdd)
{
listA.Add( new itemToAdd());
}
Which did not work. So how can I go about doing something like this? The objects are constantly growing and I don't want to have to put an if for every derived object I add. I should also mention, not sure if this will have any bearing on the solution, I've been using folders to organize the .cs files. So I have all of the derived classes in a folder named "Types" so to create a new instance of that object I have to type:
listA.Add(new Types.TypeA());
listA.Add(itemToAdd);? Is there some reason you need to create new objects before adding them to the list?