A template for calling a method that takes the most derived form of the passed object

I was surprised when I came across this situation and realized that I did not know what the best solution was.

Let's say I have three types:

class A { } class B : A { } class C : A { } 

And the following three methods:

 DoSomething(A a){ } DoSomething(B b){ } DoSomething(C c){ } 

I have a List<A> that contains objects of type B and C

I would like to do this:

 foreach(A a in list) { DoSomething(a) } 

and call the method that most closely matches the base type, but of course it will always call DoSomething(A a)

I would rather not have a bunch of type checking to get the correct method call, and I don't want to add anything to classes A, B or C.

Is it possible?

+4
source share
3 answers

This is a fairly well-known problem with virtual dispatch in statically typed languages: it processes only one ( this ) parameter "practically"; for all other parameters, the method call involves using a static argument type. Since your list is list A , the code will always overload A

You will need multiple sending to achieve this goal, and since the language does not provide this out of the box, if you do not switch to dynamic , so you will either have to make a switch or implement it yourself. There are many trade-offs to make when making this decision (as well as when deciding how to send multiple times if necessary), so don't do this easily.

+7
source

You pay the cost of performance, but one easy way to achieve this is to use dynamic linking at run time. Just pass the dynamic argument:

 foreach(A a in list) { DoSomething((dynamic)a); } 
+3
source

If you want to use the dynamic keyword, I think something like

 DoSomething((dynamic)a); 

will do the job for you.

Otherwise with static types you could say

 void DoSomething(A a) { var aAsB = a as B; if (aAsB != null) DoSomething(aAsB); var aAsC = a as C; if (aAsC != null) DoSomething(aAsC); // general A case here } 

but it could be what you call a bunch of type checking.

+3
source

All Articles