How do I call the correct overloaded function at runtime?
How to call the correct overloaded function given by an object reference 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);
}
Maybe this can be done using reflection?
+1
Sandeep Datta
source
to share
3 answers
Ok, as soon as I hit the post, I remembered that this can actually be done using reflection ...
var methInfo = typeof(Test).GetMethod("MyToString", new Type[] {o.GetType()});
methInfo.Invoke(this, new object[] {o});
+3
Sandeep Datta
source
to share
You can just use ternary operators to code this using one clean line of code:
MyToString(o is string ? (string)o : o);
+1
mbillard
source
to share
Why not have a toString () function in the actual object itself? This way you can call myObj.toString () and the relative output is specified. Then you don't need to make any comparisons.
0
Kezzer
source
to share