In the code below I'm (wrongfully apparently) expecting that method of the more specific (derived if you will) type, to be bound/called:
using System;
public class Program
{
public static int integer = 52;
public static Program program = new Program();
public static void Main()
{
TestReturn(program); // this works as expected all the way
TestReturn(integer); // 1. this not quite...
}
public static T TestReturn<T>(T t) // 2. TestReturn<Int32> all good...
{
Console.WriteLine("In TestReturn<" + typeof(T) + ">");
return (T)Extensions.Undefined(t); // 3. wrong call
}
}
public static class Extensions
{
public static object Undefined(this object t) // 4. this is called, instead of (5)
{
Console.WriteLine("In Undefined(obj)");
return null;
}
public static int Undefined(this int b) // 5. this is expected to be called
{
Console.WriteLine("In Undefined(int)");
return int.MinValue;
}
}
Output:
In TestReturn<Program>
In Undefined(obj)
In TestReturn<System.Int32>
In Undefined(obj)
Run-time exception (line 17): Object reference not set to an instance of an object.
Can someone tell why is this happening and how to do it in order to work as I intended?