Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics and calling overloaded method from difference class - precedence issue [duplicate]

First of all, sorry for the title, but I couldn't think about anything better ...

My problem can be presented by simple code sample:

public static class Test<T>
{
    public static int GetInt(T source)
    {
        return Convert.ToInt32(source);
    }
}

public static class Convert
{
    public static int ToInt32(byte source)
    {
        return 30;
    }

    public static int ToInt32(object source)
    {
        return 10;
    }
}

Why does Console.WriteLine(Test<byte>.GetInt(20)); prints 10, instead of 30?

I always thought that generics in .NET are resolved by JIT during runtime. Why then jitter isn't smart enough, to find out that there is ToInt32(byte) method, which suits our byte parameter type here?

This behavior makes Convert static class methods call result in boxing/unboxing operations for simple types.

like image 280
MarcinJuraszek Avatar asked Aug 15 '13 13:08

MarcinJuraszek


1 Answers

The compiler has to decide at compile time which method to choose. It doesn't emit any code to decide at runtime which of the two overloads to pick. Because you haven't provided any evidence to the C# compiler that GetInt(T source) only works with byte structures, the compiler has to pick the other overload.

Or let me put it in a different perspective: if you remove the ToInt32(object) overload, your program fails to compile.

like image 101
Steven Avatar answered Oct 28 '22 15:10

Steven