Nullable types and Boxing in C# 2.0

Hi

If we try boxing on a nullable type, the boxing will only take place if the object is not null. Meaning that if the HasValue is true then only object will be boxed otherwise instead of boxing the object reference is simply assigned to null.

bool? B1 = null;

object obj = B1;

// obj is null;

If the object is non-null, then boxing takes place. Only the underlying type that the nullable object is based upon is boxed. The system.Nullable that wraps the value is not boxed. These objects can also be unboxed into the nullable types like this.

bool? B2 = (bool?)obj;

This behavior provides two advantages. Firstly the nullable objects can be tested for null and secondly that the boxed nullable types fully support the functionality of the underlying type.

Hope this helps
Thanks
Vikram


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

Feedback

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