Nullable Types & Why we need them?

The .NET Framework stores value types in the stack and implicitly initializes them to their default values. For example, an int gets initialized to 0, a bool to false, and so on.
In database missing information in records represented by null values. 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#.

Nullable variable= null;
int? variable= null;

You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;

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.
GetValueOrDefault – Return value stored by Nullable type variable or the value passed in function.
There are two overload of this function.
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
age = todays date – birthdate;

Leave a comment

Filed under C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s