According to the answer to C#: Passing null to overloaded method - which method is called?, nulls seem to carry type information. In fact, I can also use
class Program
{
static void Method(TypeA a)
{
Console.Write("Output of Method(TypeA a):");
Console.WriteLine(a); // Prints nothing, on account of the null.
}
static void Method(TypeB b)
{
Console.Write("Output of Method(TypeB b):");
Console.WriteLine(b); // Also prints nothing, on account of the null.
}
static void Main()
{
var a = (TypeA)null;
var b = (TypeB)null;
Method(a);
Method(b);
}
}
class TypeA { }
class TypeB { }
Which yields
Output of Method(TypeA a):
Output of Method(TypeB b):
What's going on here?
No, the null itself doesn't carry the type information. The cast just tells the compiler what the type of the variables a
and b
should be... it can't tell without the cast, because null
is convertible to any reference type or nullable type.
The types of those variables are then used in overload resolution. Don't forget that the choice here is simply made at compile-time - it doesn't involve the execution-time value of the argument at all.
Your code is precisely equivalent to:
TypeA a = null;
TypeB b = null;
Method(a);
Method(b);
If you used dynamic typing, so that the overload resolution was performed at execution-time instead, you'd get a failure:
dynamic foo = (TypeA) null; // Or without the cast. It makes no difference.
Method(foo); // RuntimeBinderException at execution time, due to ambiguity
See more on this question at Stackoverflow