You can use dynamic typing - that will perform overload resolution at execution time with the actual type of the object that item
refers to. You can simply change the iterator type to dynamic
like this:
public void DoSomethingWithList(List<FooBase> list)
{
foreach (dynamic item in list)
{
DoSomething(item);
}
}
Note that if you end up with a FooBase
in your list which isn't a MyFoo<T>
, you'll get an execution time failure. You can avoid that (if you want) by providing another overload:
public void DoSomething(FooBase x)
{
// This will be called for any items in the list that aren't
// MyFoo<T>
}
Disadvantages of this approach:
- It has some performance impact; whether that's significant or not will depend on your app, but you should test it.
- You lose compile-time type safety.
- It doesn't work before C# 4, which is when
dynamic
was introduced.
If you can avoid getting into this situation by redesigning a bit, that's often a good idea... but sometimes you really do need something like this.