What is the default value of the nullable type "int?" (including question mark)?
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?)
Solution 1:
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 isint
), a struct. (reference) - The
Nullable<T>
type has a bool HasValue member, which whenfalse
, makes theNullable<T>
instance "act like" anull
value. In particular, the Nullable<T>.Equals method is overridden to returntrue
when aNullable<T>
withHasValue == false
is compared with an actualnull
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# isfalse
(reference). Therefore, theHasValue
property of a defaultNullable<T>
instance isfalse
; which in turn makes thatNullable<T>
instance itself act likenull
.
Solution 2:
I felt important to share the Nullable<T>.GetValueOrDefault()
method which is particularly handy when working with math computations that use Nullable<int>
aka int?
values. There are many times when you don't have to check HasValue
property and you can just use GetValueOrDefault()
instead.
var defaultValueOfNullableInt = default(int?);
Console.WriteLine("defaultValueOfNullableInt == {0}", (defaultValueOfNullableInt == null) ? "null" : defaultValueOfNullableInt.ToString());
var defaultValueOfInt = default(int);
Console.WriteLine("defaultValueOfInt == {0}", defaultValueOfInt);
Console.WriteLine("defaultValueOfNullableInt.GetValueOrDefault == {0}", defaultValueOfNullableInt.GetValueOrDefault());