What is the difference between null and (type)null?

Viewed 316

Note: THIS IS NOT A DUPLICATE. This question asks why it is even possible to cast a null, my question is what is the difference between null and (type)null to begin with.


In this reference (from the MSDN C# reference), it is said that this code:

expression as type 

is equivalent to this code ("except that the expression variable is evaluated only one time"):

expression is type ? (type)expression : (type)null  

It made me wonder, what's the point of the null casting? How is this different from:

expression is type ? (type)expression : null  

Thanks!

2 Answers

Look at this example project:

static void Main(string[] args)
{
    //Error: The call is ambigious between the following methods or properties: ShowMessage(FirstClass), ShowMessage(SecondClass)
    ShowMessage(null);
    //Here it is known which type is being used
    ShowMessage((FirstClass)null);
}

private static void ShowMessage(FirstClass value)
{
    System.Console.WriteLine(value);
}

private static void ShowMessage(SecondClass value)
{
    System.Console.WriteLine(value.ToString());
}

class FirstClass { }
class SecondClass { }

Therefor, null and (FirstClass)null is not the same. With (FirstClass)null you define it explicitly as the nullable type FirstClass (class is nullable as reference type) that is null. The other null is just ... well null and must be cast implicitly to the needed nullable type.

Beware: If you'd replace

ShowMessage(NotFirstClassObj as FirstClass)

with

ShowMessage(NotFirstClassObj is Firstclass ? (FirstClass)NotFirstClassObj : null)

It still works because the compiler can still derive the correct type. But this may be the reason why it's (type)null in the documentary.

The documentation states The code is equivalent to keyword being equivalent. You could remove the cast and the result would be the same as that is also equivalent to expression as type but why mention every possible functional equivalency?


what is the difference between null and (type)null to begin with

There is no difference in this case. They equate to the same thing. The author probably chose to use (type)null because it more clearly conveys how as works.

Related