Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#
Article

Convert & Parse are Nice, But What If You Need to Convert to a Nullable Type?

Rate me:
Please Sign up or sign in to vote.
4.14/5 (6 votes)
1 Nov 2007CPOL2 min read 26.7K   16   2
A class to convert primitive types to their nullable counterparts

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:

C#
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:

C#
/// <summary>
/// Converts the System.String representation of a number in a 
/// specified base to an equivalent 32-bit signed integer, or null.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
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

License

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


Written By
Web Developer
United States United States
Scott is a senior developer in the Montgomery Alabama area. He is married with two children and one dog.

Comments and Discussions

 
Generalif you pass a null to most of these it will cause an exception [modified] Pin
sflande13-Dec-07 4:24
sflande13-Dec-07 4:24 
GeneralValid Data Issue Pin
Brady Kelly7-Nov-07 8:54
Brady Kelly7-Nov-07 8:54 

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

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