1

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?

3 Answers 3

3

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});
Sign up to request clarification or add additional context in comments.

Comments

1

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

MyToString(o is string ? (string)o : o);

Comments

0

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.

1 Comment

This is just an example demonstrating my actual problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.