The default value of a nullable value type represents null , that is, it's an instance whose Nullable<T>. HasValue property returns false .
It is a shorthand for Nullable<int> . Nullable<T> is used to allow a value type to be set to null . Value types usually cannot be null.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
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)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.null
. 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
.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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With