Notion of System.Nullable - A Look

0 comments
C# has lots of flexibilities and hooks to turn around things that was impossible for other languages. One of such thing is the introduction of Nullable Types. Here is a discussion of how you could use Nullable to make sure your code works well for null values in Value Types.

Why System.Nullable?
System.Nullable is the only structure that supports the storage of Null as a valid range of values. Generally in case of structures it cannot store null values in it. Say for instance :

Int32 is a structure. When you specify
int x;

It will automatically assign 0 to x. This is same as
int x = default(int);

Generally structures always recursively call default to initialize the value of it. Say for instance :
struct MyCustomStructure
{
     public int m;
     public int n;
 }

Here, defined a custom structure MyCustomStructure. If you declare an object of it like :
MyCustomStructure myobj;

It will assign myobj to its default. You cannot assign null to myobj. The only way out to this situation is Nullable.
MyCustomStructure myobj = null; //throws exception
Nullable<MyCustomStructure> myobj = null; //works fine

Hence you can see, you should always use Nullable for a structure if you want to store the value of null to a structure. For data centric applications, we generally need to keep a variable out of the scope of valid values so that the variable can have a value which might identify the value as nothing. Null is taken as nothing, but in case of normal structures it does not allow us to do that. If you store nothing to an integer, it will automatically initialize to 0. But for any application 0 might be a valid value. So you cannot exclude the 0 from the range of data. Hence you need Nullable to workaround this issue.

How to use Nullable 
Nullable is simple. You can declare nullable value types using Nullable and start using it. The default(Nullable) is null.  You can see above how you could declare a nullable type. 
C# 2.0 comes with a new Question mark following data type designator which allows you to declare Nullable type. So,
//Nullable<MyCustomStructure> myobj = null; 

MyCustomStructure? myobj = null; 

Works the same way.

Any Nullable variable has few properties.
  1. HasValue : Returns true when object has a value in it. 
  2. Value : returns the actual value which is stored within the variable. (this is the object of T)

0 comments: