C# Convert string to nullable type (int, double, etc...)

Posted by Nathan Koop on Stack Overflow See other posts from Stack Overflow or by Nathan Koop
Published on 2009-04-21T15:10:03Z Indexed on 2010/04/22 6:33 UTC
Read the original article Hit count: 190

I am attempting to do some data conversion. Unfortunately, much of the data is in strings, where it should be int's or double, etc...

So what I've got is something like:

double? amount = Convert.ToDouble(strAmount);

The problem with this approach is if strAmount is empty, if it's empty I want it to amount to be null, so when I add it into the database the column will be null. So I ended up writing this:

double? amount = null;
if(strAmount.Trim().Length>0)
{
    amount = Convert.ToDouble(strAmount);
}

Now this works fine, but I now have five lines of code instead of one. This makes things a little more difficult to read, especially when I have a large amount of columns to convert.

I thought I'd use an extension to the string class and generic's to pass in the type, this is because it could be a double, or an int, or a long. So I tried this:

    public static class GenericExtension
    {
        public static Nullable<T> ConvertToNullable<T>(this string s, T type) where T: struct
        {
            if (s.Trim().Length > 0)
            {
                return (Nullable<T>)s;
            }
            return null;
        }
    }

But I get the error: Cannot convert type 'string' to 'T?'

Is there a way around this? I am not very familiar with creating methods using generics.

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics