Not everything that looks like (SomeType)expression
is really a cast, in C#. Sometimes the expression needs to acquire a type that it didn't have already. Some other examples:
var a = (short)42;
var b = (Func<int, int>)(i => i + 1);
var c = (IConvertible)"Hello";
In each of these cases, one could also have written the type on the left, instead of var
, if one preferred that. But this is not always the case when the expression is a part of a larger expression, say:
CallOverloadedMethod((short)42); // CallOverloadedMethod has another overload that we don't want
var y = b ? x : (IConvertible)"Hello"; // the ?: operator might not be able to figure out the type without this hint
In your example the literal null
has no type in itself. In some cases, like when choosing between many overloads, like when using the ternary ?:
operator, or when declaring a variable with var
syntax, it is necessary to have an expression that is still null
but also carries a type.
Note that overloads also includes operators, for example in:
public static bool operator ==(Giraffe g1, Giraffe g2)
{
if (g1 == (object)null && g2 != (object)null
|| g1 != (object)null && g2 == (object)null)
{
return false;
}
// rest of operator body here ...
}
the (object)null
syntax is used to ensure the user-defined overload of ==
is not called recursively.