Nullable Types in C-sharp .net

Why we are calling struct variables as value type and why they can not be null?

Because they always contains some values of the same type and they can not be null and that's why we are creating any structure in c# we must have to initialize all members in its constructor with some values. In .net all intrinsic types are structure and they are value types so they can't be null.

Why nulablel is required for value types?

In some scenario we can not directly map value type variables with other type system. Like in database columns values can be null and in case of web services suppose java web service is returning null for DateTime because Java DateTime is reference type and it can be null but .net DateTime is value type and it can't be null so it may create problem that is why nullable type is re required.

To improve avoidance these kind of situations MS provided System.Nullable<T> class.

In C# we can declare nullable type either using Nullable<Int32> class or Int32?. If you want to declare nullable value type then then declare them with question mark, C# complier will translate this notation with System.Nullable<T>. We can also perform conversions and and type casting on nullable types.


int? temp = null;

float? f1 = 5.0f;

temp = (int)f1;

double? d1 = temp;

We can use all operators on nullable types, on unary operators if operand is null then result will be null,

On binary operators if any of operand is null then result will be null.

On equality operator result will be true when both are null and result will be false one is not null and other is null and on rational operators result will be false if either operand is null.

CLR supports boxing, unboxing , GetType() and interface method calling support on nullable types.

// Boxing Example

int? temp1 = null;

object obj = temp1; // obj is null

Console.WriteLine("obj is null={0}", obj == null); 

temp1 = 5;

obj = temp1; // obj refers to a boxed int

Console.WriteLine("obj's type={0}", obj.GetType());

// Unboxing Example

object obj = 5;

Int32? a = (Int32?)obj; //a = 5

obj = null;

Int32 b = (Int32?)obj; //b = null


GetType() on nullable type will not return Syatem.Nullable<T> it will return only actual type T.

int? i = null;

i.GetType().ToString(); will return "System.Int32"

blog comments powered by Disqus