Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I dispatch to a method based on a parameter's runtime type in C# < 4?
    text
    copied!<p>I have an object <code>o</code> which guaranteed at runtime to be one of three types <code>A</code>, <code>B</code>, or <code>C</code>, all of which implement a common interface <code>I</code>. I can control <code>I</code>, but not <code>A</code>, <code>B</code>, or <code>C</code>. (Thus I could use an empty marker interface, or somehow take advantage of the similarities in the types by using the interface, but I can't add new methods or change existing ones in the types.)</p> <p>I also have a series of methods <code>MethodA</code>, <code>MethodB</code>, and <code>MethodC</code>. The runtime type of <code>o</code> is looked up and is then used as a parameter to these methods.</p> <pre><code>public void MethodA(A a) { ... } public void MethodB(B b) { ... } public void MethodC(C c) { ... } </code></pre> <p>Using this strategy, right now a check has to be performed on the type of <code>o</code> to determine which method should be invoked. Instead, I would like to simply have three overloaded methods:</p> <pre><code>public void Method(A a) { ... } // these are all overloads of each other public void Method(B b) { ... } public void Method(C c) { ... } </code></pre> <p>Now I'm letting C# do the dispatch instead of doing it manually myself. Can this be done? The naive straightforward approach doesn't work, of course:</p> <blockquote> <p>Cannot resolve method 'Method(object)'. Candidates are:</p> <ul> <li>void Method(A)</li> <li>void Method(B)</li> <li>void Method(C)</li> </ul> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload