tags:

views:

249

answers:

3

Hi All,

How do I call the correct overloaded function given a reference to an object based on the actual type of the object. For example...

class Test
{
 object o1 = new object();
 object o2 = new string("ABCD");
 MyToString(o1);
 MyToString(o2);//I want this to call the second overloaded function


 void MyToString(object o)
 {
  Console.WriteLine("MyToString(object) called.");
 }

 void MyToString(string str)
 {
  Console.WriteLine("MyToString(string) called.");
 }
}

what I mean is there a better option than the following?

if(typeof(o) == typeof(string))
{
 MyToString((string)o);
}
else
{
 MyToString(o);
}

May be this can be done using reflection?

+1  A: 

Ok as soon as I hit post I remembered this can indeed be done using reflection...

var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()});
methInfo.Invoke(this, new object[] {o});
SDX2000
A: 

Why not have a toString() function in the actual object itself? That way you can call myObj.toString() and the relative output is given. Then you don't have to do any comparisons.

Kezzer
This is just an example demonstrating my actual problem.
SDX2000
+1  A: 

You could just use ternary operators to code this using a single clean line of code:

MyToString(o is string ? (string)o : o);
GoodEnough
Does that even compile?
leppie
And run like you expect it?
leppie
I'm pretty sure it will.
GoodEnough