I am trying to create a generic method in C#, which will call different methods based on the argument datatype in its body and process their result afterwards. I am trying t
Is there any way correct this behavior?
It's already the correct behaviour according to the C# language specification. The overload of Func
called within FuncWrap
is normally determined at compile time, so it can't pick a different Func
overload based on the execution-time type.
One way of changing the behaviour, however, is to use dynamic typing:
static void FuncWrap<T>(T val)
{
Console.Write("Wrap: ");
dynamic x = val;
Func(x);
}
That will now perform overload resolution at execution time based on the actual type of the value of x
. This incurs a performance cost, but should do what you want it to.
Alternatively, you could hard-code knowledge of the overloads:
static void FuncWrap<T>(T val)
{
Console.Write("Wrap: ");
if (typeof(T) == typeof(string))
{
Func((string)(object)val);
}
else if (typeof(T) == typeof(int))
{
Func((int)(object)val);
}
else
{
Func(val);
}
}
That's clearly pretty horrible though.