Nullable type in C#

SheoNarayan
Posted by in C# category on for Beginner level | Views : 5130 red flag

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.

  1. Value type eg. int, char, date. A data type is a value type if it holds the data within its own memory allocation.
  2. 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

HasValue property is the boolean property. If nullable variable is assigned any non-null value, it returns true otherwise false.

Value Property

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.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)