Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
Variables are of two types.
- Value type eg. int, char, date. A data type is a value type if it holds the data within its own memory allocation.
- Reference type eg. string, object. A reference type contains a pointer to another memory location that holds the data.
For more details on Value types and Reference type of variable, please read http://msdn.microsoft.com/en-us/library/t63sy5hs(VS.80).aspx
Reference types variable can be assigned null but value types of variables like integer can't because they can't contain reference, even the reference of nothing.
int i = 0;
The above statement shall throw error because we are trying to store null in the integer variable.
To avoid this we can use nullable modifier like this.
int? ii = null;
In the above code, ii is the nullable type of variable that can store either null or any integer type of variable. When a variable is declared as nullable, its extends two properties called HasValue and Value. Both property are public and read-only.
Normal Integer Variable Intellisense
Nullable Integer Variable Intellisense - Notice HasValue and Value property
HasValue property is the boolean property. If nullable variable is assigned any non-null value, it returns true otherwise false.
Value property is only accessible successfully when there is some non-null value in the nullable type of variable otherwise an exception is thrown.
If we want to set the default value of nullable type, we can use coalescing operator (??). For more details on coalescing operator, read http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx. The default value must be of the same type as nullable variable. The default value is returned if the nullable type is null.
int? ii = null;
ii = 4;int ij = ii ?? 5;
Here ij variable will have 4 but if we comment the 2nd line (ii = 4) then 5 will be stored in ij as default value.