Click here to Skip to main content
Click here to Skip to main content

C# Nullable Types…Subtlety

By , 1 Apr 2009
Rate this:
Please Sign up or sign in to vote.

While moderating posts over on the Asp.Net forums, I ran into a thread containing questions about using Nullable types.

Nullable types are a simple concept: Allow value types to have the value of null. Typically, an integer or float cannot be null: When in scope, they always exist and therefore must have a numeric value (zero is not null, it is a numeric value).

Here is the subtlety (or in technical terms, a really ooky statement):

Nullable types with the value of null are not really null.

Look at this code:

 int Test1 = 0;  // standard value type
 int? Test2 = null; // nullable value type  
 Object Test3 = null; // reference type

 Response.Write("Test1: " + Test1.ToString() + "<br />");
 Response.Write("Test2: " + Test2.ToString() + "<br />");
 //Response.Write("Test3: " + Test3.ToString() + "<br />");

 // Output:
 //
 // Test1: 0 // correct
 // Test2: // no exception, what? but it's null!
 //
 // If Test3 is allowed to run, we get:
 // "Object reference not set to an instance of an object."

It is odd that we can access Test2 when its value is null but we get no output string.

Microsoft's web site correctly describes nullable types (http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx):

"A nullable type can represent the correct range of values for its underlying value type, plus an additional null value."

But most of us gloss over descriptions like that and until you see it demonstrated, you may not truly understand.

I hope someone finds this useful, Steve Wellens.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Steve Wellens
EndWell Software, Inc.
United States United States
I am an independent contractor/consultant working in the Twin Cities area in Minnesota. I work in .Net, Asp.Net, C#, C++, XML, SQL, Windows Forms, HTML, CSS, etc., etc., etc.

Comments and Discussions

 
GeneralNullable Type in .NET Pingroupelizas6-May-10 21:36 
GeneralPoint worth mentioned PinmemberDebo_Net6-Jan-10 7:02 
GeneralRe: Point worth mentioned PinmemberDebo_Net6-Jan-10 7:05 
GeneralRe: Point worth mentioned PinmemberSteve Wellens6-Jan-10 7:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 1 Apr 2009
Article Copyright 2009 by Steve Wellens
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid