When should we use Nullable types in c#?

C# has two type of data types. Value type and reference types. String is reference type and int is value type. A reference type can be assigned with a null value like string s = null; But you can not assign a null value direcly to a inteer. like int a = null . So to make the value type accept a null value, nullable types are used.

Nullable types can represent all the values of an underlying type, and an additional null value.

To represent null in a value type, you must use a special construct called a nullable type. It is represented using ? symbol.

Int32? I=null; //now its ok

Now scenario when nullable types commanly used is in database programming where calss is map to table with nullable columns.
• If the columns are reference type that is String such as (email address and customer address), there is not a problem as you can defined it as null in C#
• But if the columns are value type that is double such as (customer account balance), you cannot map it to C# without using nullable types.

Checking value:

int? Accountbalance

if (Accountbalance.HasValue)
{
// Write code
}

=====================================================================
Nullable<T> is useful for when you need a possible invalid state for a value type, or if the data is being retrieved from a database that may contain a null value for the column.

It is worth mentioning that the following is the same:

Nullable<int> myNullableInt; ==> int? myNullableInt;

=====================================================================

In addition   this following property useful:

public bool? IsHappy { get; set; }

This allows me to have a tri-state boolean value: yes, no, not answered.

=====================================================================

A nullable type can be cast to a regular type, either explicitly with a cast, or by using the Value property. For example:
int? n = null;

//int m1 = n;      // Will not compile.
int m2 = (int)n;   // Compiles, but will create an exception if x is null.
int m3 = n.Value;  // Compiles, but will create an exception if x is null.
=====================================================================
 
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s