Helpful Extension Methods: TryParse[x]()

2013-11-26 7:22 PM

Parsing into primitives in C# is not quite as nice as it should be, particularly if you're attempting to parse and soft-failing if the parse doesn't work. For instance, if we want to attempt to parse a string to a DateTime?, which is null if the parse fails and correctly set if it succeeds, we would have:

var input = "2013-01-10 06:11:20 AM";
DateTime? asDateTime;
DateTime target;
var success = DateTime.TryParse(input, out target);
if (success)
{
    asDateTime = target;
}
else
{
    asDateTime = null;
}

This isn't good - it's really chunky and gross. Additionally, I hate the out parameter modifier: my opinion is that classes and Nullable<T>s completely supplant any value it offers, and that it just promotes poor coding practice.

So let's wrap up the outs with extension methods so we never have to deal with these crummy parsing wrappers!

DateTime

Here's how we can wrap it up pretty easily:

public static DateTime? AsDateTime(this string input)
{
    DateTime result;
    if (DateTime.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

And to illustrate the utility, it makes the original code snippet much more clear:

var input = "2013-01-10 06:11:20 AM";
var asDateTime = input.AsDateTime();

That's great! But let's keep in mind that there are several other primitives...

int

Fortunately, it's really easy to modify this code for most primitives in .NET - just replace DateTime with whatever target you have - in this circumstance, int:

public static int? AsInt(this string input)
{
    int result;
    if (int.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

decimal

Wouldn't it be great if we could just write this as a generic? Unfortunately, all of the parse methods are static, implementation-specific methods that can't be called generically.

public static decimal? AsDecimal(this string input)
{
    decimal result;
    if (decimal.TryParse(input, out result))
    {
        return result;
    }
    return null;
}

The rest is up to you

At least having some extension methods to parse with less headache helps out a lot. Extend these to any other structs or classes that give you parsing headaches, and your code gets better little by little!