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

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

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

 class MyClass { public int? MyNullableInt; } 

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

+45
c #
Mar 19 '15 at 19:59
source share
3 answers

The default value for int? - and for any type with a null value using the type? ad is null .

Why is this so:

  • int? is syntactic sugar for the type Nullable <T> (where T is int ), a structure. ( link )
  • The Nullable<T> has a bool HasValue element that, when false , makes the Nullable<T> instance valid as "a null . In particular, the Nullable <T> .Equals method is canceled to return true when Nullable<T> with HasValue == false compares with the actual null value.
  • From C # Language Specification 11.3.4, the initial default value for an instance of the structure is all fields of type structure type set by default, and all of these are fields of type reference structure set to null .
  • The default value for the bool variable in C # is false ( link ). Therefore, the Nullable<T> instance's HasValue property is false by default; which in turn makes the instance of Nullable<T> , as null .
+69
Mar 19 '15 at 19:59
source share

It was important for me to share the Nullable<T>.GetValueOrDefault() method, which is especially convenient when working with mathematical calculations using the Nullable<int> aka int? values int? . There are many times when you do not need to check the HasValue property, and you can simply 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()); 

Command line with code shown above

+10
Nov 06 '15 at 2:45
source share
 var x = default (int?); Console.WriteLine("x == {0}", (x == null) ? "null" : x.ToString()); 
0
Mar 19 '15 at 20:02
source share



All Articles