How to invoke Display method extending object class?
static class Tools
{
public static void Display<T>(this T t)
{
Console.WriteLine("generic: " + t.GetType());
}
public static void Display(this object o)
{
Console.WriteLine("object: " + o.GetType());
}
}
class Program
{
static void Main(string[] args)
{
int i = 100;
// all will invoke the generic version.
Tools.Display<int>(i);
i.Display();
Tools.Display(i);
}
}
I can’t remember where in the standard it says it, but C# prefers to call the most specific overload. With generics, the generic version of the function will almost always take preference. So while an
intis anobject, it better fits theDisplay<T>(T)thanDisplay(object), since the realization of the generic (Display<int>(int)) is an exact match. Add the fact that C# can figure out which type belongs in theTby itself and you see the behavior you’re experiencing.So, you must explicitly cast to an object to call the object version:
Alternatively:
And you’ll have a curious (but sensible) issue if you do:
This will call the
objectversion in the first case and the generic one in the second. Fun times with parameters!