I want to use methods overload to get different result according to different generic types. It does not work. My code show it clearly.
static class Helper
{
public static bool Can(int i)
{
return true;
}
public static bool Can(Object o)
{
return false;
}
}
class My<T>
{
public static bool can = Helper.Can(default(T));
}
Console.WriteLine(Helper.Can(default(int)));//True,it is OK
Console.WriteLine(My<int>.can);//false?? why the overload doesn't work
Console.WriteLine(My<Object>.can);//false
Why My<int>
calls Helper.Can(Object o) rather than Helper.Can(int i)?
It doesn't work that way.
Overloads are resolved entirely at compile-time; generic type parameters are resolved at runtime.
Since the compiler doesn't know that T
is int
, your code will always call Can(Object)
.
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