I have an IEnumerable<BaseClass>
that may contain some objects of type SubClassOfBaseClass
. I also have an overloaded method with 2 overloads, each one taking either BaseClass or SubClassOfBaseClass.
When I iterate through the IEnumerable
and call the overloaded method for each member, passing it the member as a parameter, it always calls the overload meant for BaseClass, never SubClassOfBaseClass.
Is there an elegant way to get it to call the correct overload - other then manually checking each member of the IEnumerable and cating it to the correct type?
Example code:
public class BaseClass {
}
public class SubClassOfBaseClass : BaseClass {
}
public class Program {
private static void Method(BaseClass item) {
Console.WriteLine("base class!");
}
private static void Method(SubClassOfBaseClass item) {
Console.WriteLine("sub class!");
}
public static void Main(string[] args) {
var items = new List<BaseClass>();
items.Add(new BaseClass());
items.Add(new SubClassOfBaseClass());
foreach (var item in items) {
Method(item);
}
}
}
The resulting output would be:
base class!
base class!
...but I need it to be
base class!
sub class!