What is the default value of the nullable type "int?" (including question mark)?

Jon Schneider picture Jon Schneider · Mar 19, 2015 · Viewed 67.7k times · Source

In C#, what is the default value of a class instance variable of type int??

For example, in the following code, what value will MyNullableInt have if it is never explicitly assigned?

class MyClass
{
    public int? MyNullableInt;
}

(It seems likely that the answer is almost certainly either null or 0, but which of those is it?)

Answer

Jon Schneider picture Jon Schneider · Mar 19, 2015

The default value for int? -- and for any nullable type that uses the "type?" declaration -- is null.

Why this is the case:

  • int? is syntactic sugar for the type Nullable<T> (where T is int), a struct. (reference)
  • The Nullable<T> type has a bool HasValue member, which when false, makes the Nullable<T> instance "act like" a null value. In particular, the Nullable<T>.Equals method is overridden to return true when a Nullable<T> with HasValue == false is compared with an actual null value.
  • From the C# Language Specification 11.3.4, a struct instance's initial default value is all of that struct's value type fields set to their default value, and all of that struct's reference type fields set to null.
  • The default value of a bool variable in C# is false (reference). Therefore, the HasValue property of a default Nullable<T> instance is false; which in turn makes that Nullable<T> instance itself act like null.