Working with nullable types in C#

Hi

One of the new features in the C# language is the support for nullable data types. If in your application you are dealing a lot with database having null fields and this will be very helpful although the nullable data types are useful in other situation also.

A data type that can contain defined data type or null value is nullable data type. Defing the nullable type is very simple. All we need to use is the ? modifier.

Normal declaration without nullable type

Double d1=12;

Declaration with nullable type.

Double? D2= 12;

Or

Double? D2= null;

Nullable types are supposed to be used in the same way as we use regular value types. Infact we can also do implicit conversions between nullable and non nullable types of same type.

Lets say we have 2 variable

Double? nFirst = null;

Double Second = 20000;

 

nFirst = Second;   

nFirst = 12;      

Second = nFirst;   

All the above statements would be correct. 

nFirst = null;     

The above statement is also valid. But the below statement will give an exception since Second is not a nullable type.

Second = nFirst;   

To help avoid throwing an exception, we can use the nullable HasValue property to determine if the value is null or not.
Hope this helps
Thanks
Vikram

Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Posted on 1/12/2007 6:58:22 PM

This post explains very basic thing nicely. Can you provide the small example of this type in ado.net application as this is meant for used in database related application

Posted on 1/13/2007 9:17:06 AM

Good tip for beginners...

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia