Why does this program output Generic Value and not Hello world!:
using System;
class Example
{
public static void Print<T>(T value)
{
Console.WriteLine("Generic Value");
}
public static void Print(string value)
{
Console.WriteLine(value);
}
public static void GenericFunc<T>(T value)
{
Print(value);
}
static void Main()
{
GenericFunc("Hello world!");
}
}
How is the generic method parameter being translated under the hood of C#?
Overload resolution is only done at compile-time.
Since GenericFunc<T> doesn't know whether T is a string or something else at compile-time, it can only ever use the Print<T>(T value) "overload".
Using dynamic, you can change this to a dynamic dispatch, and get the behaviour you expect:
Print((dynamic)value);
This makes the overload resolution happen at runtime, with the actual runtime type of value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With