Home » c# » c# – how to change an object type to its actual type?

c# – how to change an object type to its actual type?

Posted by: admin February 21, 2020 Leave a comment

Questions:

I have an object which is actually string/integer.
I can get its type by obj.GetType().
In the runtime I know it is a string.
The problem is a function only accepts string or integer.
If I wrote

int cnt = 0;
public object why()
{
    cnt++;
    if (cnt % 2 == 0) return 0;
    return "";
}
void A(int input) {
}
void A(string input) {
}
void Test()
{
    object obj = why();
    MethodInfo method = obj.GetType().GetMethod(nameof(A), new[] { obj.GetType() });
    //Need to call A by obj, but it threw an error :)
    method.Invoke(null, new[] { obj });
}

It returns error as it rejects object. It could work if

func((string)obj)

But I need also cater integer ( and possibly other type too later, thus it may not appropriate to apply conditional statement for the scenario)

the optimum way is changing the type of the object before assign it to the function, but I am not sure if it is possible, which is string in the example func((string)obj).

How to&Answers:

You can use reflection to get the correct method based on the type of the object. Then you can use Invoke() to actually call the method with the argument.

object obj = why();
MethodInfo method = typeof(YourClass).GetMethod(nameof(YourClass.A), new [] { obj.GetType() } );
method.Invoke(maybe_an_object_here, new [] { obj } );