Introduction
A simple, static class to help convert primitives into their .NET 2.0 nullable counterparts.
Background
"Nullable types address the scenario where you want to be able to have a primitive type with a null (or unknown) value. This is common in database scenarios, but is also useful in other situations." -- Eric Gunnerson
In my last Web project, I found myself having to do a lot of conversion of strings and other primitive types into nullable types for one reason or another. I was doing a lot of checking in a lot of places and decided to abstract all of that out into its own class. Thus, the ConvertNullable class was born.
Using the Code
If you've never seen .NET 2.0 nullable types, they are very easy to use. The syntax for using a nullable type looks like this:
int? x = 125;
if (x != null) {...}
The ConvertNullable class is static so you should just be able to drop it into your projects appCode directory and see its effects immediately. I've included conversion methods for the following types:
Byte?
bool?
DateTime?
Decimal?
Double?
Int16?
Int32?
Int64?
SByte?
Single?
UInt16?
UInt32?
UInt64?
Here is an example of how the conversion is done from one of the methods:
public static Int32? ToInt32(object value)
{
Int32 returnValue;
if (Int32.TryParse(value.ToString(), out returnValue))
{
return returnValue;
}
else
{
return null;
}
}
All the methods make use of the primitive's TryParse method. The TryParse method takes a string, and an output parameter of the primitive type as its parameters. It attempts to do the parse and returns a true or false value if it succeeded or not. If the parse was successful, it also gives you back the successfully converted item. If the value was false meaning the value could not be converted, it then returns null - thus - ConvertNullable.
Points of Interest
One thing that I had to look out for was the DateTime type. If you pass null into the TryParse of a DateTime - it will actually succeed and return a date of 01/01/0001 which is definitely not expected behavior. So in the ConvertNullable.ToDateTime method, I just had to check if a null value had been passed in first before attempting the conversion.
I hope this helps someone out there - thanks!
History
- 11/01/2007 - First submission