Nullable Types in C# - ProgramIdea

Nullable Types in C#


Nullable types can represent data type values with one more value null.

For example, a Nullable<bool> can be assigned to true, false and null value.

The syntax T? is shorthand for Nullable<T>

Need of nullable type

Reference type can store null value but value type cannot store null value, so storing null value in value type we are using nullable type.

Suppose you have a registration form that contains a field user age that is optional. If user not enter any value then what value is save in database that column field is integer type. By default sql database can store interger value as well as null value for that field. Exactly same as in C# for storing null value in a value type .Net framework introduced nullable type.

Below codes are showing benefits of nullable type means, you cannot store empty value in user age field with normal integer type but you can store empty value in user age field with nullable integer type that is the advantage of nullable types.

// You cannot define empty value
int userAge = null; // Invalid 

//You can define empty value
int? userAge = null;  // Valid

Get Values

Use HasValue property that return true if nullable data type has any value except null. Use Value property to get exact value of data type.

int? x = null; 

// 1st way
if (x.HasValue)
{
    Response.Write(x.Value);
}

// 2nd way
if (x != null)
{
    Response.Write(x);
}       

// 3rd way
if (x > 0)
{
    Response.Write(x.Value);
}

Get Default Values

You can also get stored value else default value of data type.

int? x = null;        

// Get assigned or default value
int z = x.GetValueOrDefault();

Converting nullable to non nullable values

int? x = 10; 

// Nullable to non-nullable
// make sure that value is not null
int a = (int)x;

int b = x.Value;

// Non-nullable to nullable
int? y = a;

Assigned a default value

You can take advantage of ?? sign to assign a new value for nullable type, if it has null value.

int? x = null;

int a = x ?? 10;

Boxing and Unboxing for nullable type

int? x = 10;

//Boxing
object obj = x;

Response.Write(obj.GetType());
// Output - System.Int32

// Unboxing
int? a = (int?)obj;
int b = (int)obj;