Wednesday, December 22, 2010

Nullable type -- Why we need Nullable types in programming language ?

Shout it kick it on DotNetKicks.com
What is nullable type ?
Nullable type is new concept introduced in C#2.0 which allow user to assingn null value to primitive data types of C# language. Important to not here is Nullable type is Structure type.

Why nullable types needed in programming?
In database missing information in records represented by null values even if its primitive types of data like varchar, int, datetime etc. So the problem arises when fetch data from the data base, how to represent missing null value in our program because primitive data only stores real values in C#.
For example
Consider system where I maintaining one city people records, which stores birth date and death date to calculate the age. But database stores null value in death date field for the people who is still alive.

Pseudocode code - formula for the age calculation is
//for the people who is already dead  
age = deathdate - birthdate;       
//for the people who is till alive
age = todays date - birthdate;
  

Solution 1
Before introduction of nullable vaue in older days we use some junk value to represent value is not present. For example
int a = -99;
DateTime dt = new DateTime(1901, 1, 1);

Pseudocode code for the above problem is
//for the people who is already dead  
age = deathdate - birthdate;       
//for the people who is till alive -- check date value is equal to dt i.e 1/1/1901
age = todays date - birthdate;
 
So we compare this value and get information that value is not real value.

Problem with this is we have to remember this value and have to hardcode this value in our program structure.

Solution 2
Nullable type
Syntax
Nullable<int> variable= null;
or
int? variable= null;

Properties
Nullable types has two important property
  • Hasvalue - indicate that variable contains real values or not. It returns false if variable contains no value and true if some real values is stored in it.
  • Value - Return real value stored in variable. It throws InvalidOperationException exception.
Method
GetValueOrDefault - Return value stored by Nullable type variable or the value passed in function.
There are two overload of this function.
Syntax
  • GetValueOrDefault() - returns real value or the default value of object.
  • GetValueOrDefault(T) - returns real value or the value passed.
Pseudocode Code for above problem
//variable define
DateTime? deathdate = null;

//for the people who is already dead  
if( deathdate.Hasvalue) // checking for the nullable varialbe has value or not
age = deathdate.Value - birthdate;       
//for the people who is till alive
else
age = todays date - birthdate; 

Summary
I hope now people why the Nullable feature get included in C#2.0.

Related post

No comments:

Post a Comment