How do I dispatch to a method based on a parameter's runtime type in C# < 4?

Posted by Evan Barkley on Stack Overflow See other posts from Stack Overflow or by Evan Barkley
Published on 2010-05-12T11:46:43Z Indexed on 2010/05/12 12:04 UTC
Read the original article Hit count: 265

Filed under:
|
|

I have an object o which guaranteed at runtime to be one of three types A, B, or C, all of which implement a common interface I. I can control I, but not A, B, or C. (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.)

I also have a series of methods MethodA, MethodB, and MethodC. The runtime type of o is looked up and is then used as a parameter to these methods.

public void MethodA(A a) { ... }
public void MethodB(B b) { ... }
public void MethodC(C c) { ... }

Using this strategy, right now a check has to be performed on the type of o to determine which method should be invoked. Instead, I would like to simply have three overloaded methods:

public void Method(A a) { ... } // these are all overloads of each other
public void Method(B b) { ... }
public void Method(C c) { ... }

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:

Cannot resolve method 'Method(object)'. Candidates are:

  • void Method(A)
  • void Method(B)
  • void Method(C)

© Stack Overflow or respective owner

Related posts about c#

Related posts about method