There are a couple of options here, but it really boils down to how can doStuuf
know what to do if you're going to add new derived types in the future?
So, one option is if Container
really does only contain 1 type at a time then you could make it generic:
class Container<T> where T: Base
{
public List<T> Items { get; }
}
Now when you iterate it, you know that Items
is a List of DerivedA
or DerivedB
Container<DerivedA> container = ReturnsContainerOfDerivedA();
foreach (var item in container.Items)
{
doStuff(item); // item is definately DerivedA
}
This would mean you either have multiple doStuff
methods
public void doStuff(DerivedA item){...}
public void doStuff(DerivedB item){...}
or if more appropriate you can have 1 which takes the base
public void doStuff(Base item){...}
That is the advantage of simple polymorhism!
The second option is to define doStuff
as taking a dynamic
if you're using C#3.5
public void doSomething(dynamic item){..}
But I would personally avoid this option!