C# – the type of null literal

clanguage-lawyernet

Dear all, I wonder what is the type of null literal in C#?

In Java, the null literal is of the special null type:

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type.

In C++11, there is nullptr (the recommended version of the old buddy NULL), which is of type std::nullptr_t.

I searched MSDN about C#, but the specification doesn't seem to say anything about that.

Best Answer

According to the ECMA C# language specification:

9.4.4.6 The null literal:

The type of a null-literal is the null type (§11.2.7).

11.2.7 The null type:

The null literal (§9.4.4.6) evaluates to the null value, which is used to denote a reference not pointing at any object or array, or the absence of a value. The null type has a single value, which is the null value. Hence an expression whose type is the null type can evaluate only to the null value. There is no way to explicitly write the null type and, therefore, no way to use it in a declared type. Moreover, the null type can never be the type inferred for a type parameter (§25.6.4)

So to answer your question, null is it's own type - the null type.

Although it's odd how it's not mentioned in the C# 4.0 language specification or the C# 3.0 language specification but is mentioned in the overview of C# 3.0, the ECMA C# language specification and the C# 2.0 language specification.