December 22, 2008

Nullable Types in C#

0 comments

int x = 0; //valid statement
int y = null; //compile time error

This is because we know that null is a value for reference types and since int is a value type it cannot hold the value null in it. So if there comes a situation where u need to hold null value inside an int then the solution is the Nullable Type.

Any Value Type can be Nullable Type, which means that the default value can hold the possible value in its data range as well as a new value 'null' in it. The syntax for this is,

int? x = null; //valid statement; now x is a nullable type

Also dont guess that since now x can hold null value, it can be reference type. This is wrong. What Nullable Type is like a wrapper around a value type which can hold a null value also. So the value of x is stored in stack(by default).