Developers were always looking forward to the inclusion of Nullable types in C#. I love the way it's been implemented using generics. Before we go in to the specifics of Nullable types; let's look at what is a Nullable type and it's usage.
What's a Nullable type?
A nullable type is a value type which can be assigned a null value. Type's like int/bool/double/etc... now can be assigned null values.
Usage:
A simple case for nullable type is while assigning a database column value to a value type.
Example:
int iEmpId = 0;
//Will throw an error if the DataReader value is null
iEmpId = (int)drEmployee["id"];
Now let's see how a value type can be promoted to a Nullable type with the magic of generics.
Declaring a nullable type is straight forward..
System.Nullable<int> iEmpId;
or
int? iEmpId; //that's a shorthand
iEmpId = null; //Allowed as it's Nullable
if(iEmpId.HasValue){
//do something
}
So for assigning a value from let's say a datareader, we could do something like this.
int? iEmpId = null;
iEmpId = (int?)drEmployee["id"];
if(iEmpId.HasValue){
//do something
}
Hmm that certainly makes sense, isn't it?