Murtaza Fazal's Blog

Murtaza Fazal's Blog
Murtaza Fazal's Blog

Tuesday, September 1, 2009

Nullable Type in Visual Studio 2005+

Many of us learn programming through books or in some programming course. They course starts with simple data types and ends with a good looking application but one thing most of the books or instructors forget that the first and farmost requirement of a good looking application is to have good backend programming as well. I’ve being working on C# since a long time but I never came across this Nullable type in any of the books for beginners or Professionals and to me it seemed as one of the basic knowledge that was missing.

What does Nullable do? So far when we write a small piece of code, like for instance we are taking bio-data from the user in a console based application and if he presses enter without typing anything i.e. entered nothing in that field, what would happen? And what should have happened? The user pressed enter which means it should be a null field whereas a character 13 (ASCII CODE) is saved in its place. Is that the correct thing? Definitely not, and to overcome this state most of the books teaches us to use conditions that if its equal to 13 then ignore it or do something.

In Framework 2.0 and onwards, Microsoft has provided us with Nullable type through which we can allow null values in our simple datatypes. Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)

Nullable < T >   variable;

Here T is a value type. The two forms are interchangeable. As in our example, we can use following code:

Nullable < string >  name = null;

Or what if we want to have a 3 state Boolean variable? True, False and Null? Thanks to Nullable type we can implement this within seconds by declaring our boolean variable under nullable type

Nullable < bool >  flag;

Microsoft added this feature but what’s the use of it?  Why to add another state even if we could do it through some conditions? With the use of Nullable, we can have the normal range of values of the underlying value type with additional of null value. Two fundamental members of the Nullable structure are “HasValue” and “Value” properties. If the HasValue property for a Nullable(T) object is true, the value of the object can be accessed with the Value property. If the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException. The Nullable class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations.

No comments:

Post a Comment