Nullable Types

by mgordon 7. June 2007 08:24

I’ve read, numerous times, the concepts surrounding the “null” value from a database perspective.  “Null isn’t a value but rather indicates the absence of a value”.  Null means unspecified or unknown.  There’s a good deal of flexibility and power with null.

With a string variable, you can initialize it to null and later check to see if it has been initialized by checking for a null value.  If you initialize the variable to an empty string, when you later check the value, you have to make a judgment call as to what an empty string means.  Does it mean that the variable has been set to an empty string or that it hasn’t been initialized, at all?  Initializing the variable to null allows you to make a distinction between “nothing has been specified” and “a value was specified, but it was nothing”.  

You can set a string to null, but what about an integer?  By default, an integer is initialized to zero.  So, the problem described, above, applies.  If the integer variable has a value of zero does that mean a zero was specified or that nothing was specified at all?  By using nullable types, it’s possible to get the same behavior from an integer, datetime and so on as you do for a string.

By defining your variable as a nullable integer like so

 C# 

int? integer = null  

VB

 Dim integer As Nullable(Of Integer) = Nothing  

You can get exactly the same behavior as with the string. This is especially useful when working with a database.  If you have an integer column in the database that’s mapped to an integer field on a business object.  How do you handle assigning the value if it’s null?  You probably set the integer field to 0, in this case.  I’d argue it’s more correct to use a nullable integer type for the field and set it to null.    

Tags:

.Net

Comments are closed

About the author

Mitch Gordon lives and works in the great state of Georgia.

RecentPosts

Month List