Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# overload error for generic type

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)?

like image 722
zilong Avatar asked Dec 09 '12 14:12

zilong


1 Answers

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).

like image 162
SLaks Avatar answered Oct 10 '22 17:10

SLaks