Tag Archives: Nullable types

Nullable Type

Nullable types are instances of the System.Nullable struct.

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.

Advertisements

Leave a comment

Filed under C#