Quick Tip: Parse String to Nullable Value

When you’re dealing with a system like SharePoint that returns most data as strings, it’s common to want to parse the data back into a useful numeric format. The .NET framework offers several options to achieve this, namely the static methods on System.Convert and the static Parse() methods on the various value types. However, these are limited in that they turn null string values into the default for the given type (0, false, etc) and they throw exceptions to indicate failure, which might be a performance concern.

Often, a better option is to use the static TryParse() method provided by most value types (with the notable exception of enumerations). These follow the common pattern of returning a boolean to indicate success and using an out parameter to return the value. While much better suited for what we’re trying to achieve, the TryParse pattern requires more plumbing than I care to see most of the time—I just want the value. To that end, I put together a simple extension method to encapsulate the pattern:

public delegate bool TryParser<T>(string value, out T result) where T : struct;

public static T? ParseWith<T>(this string value, TryParser<T> parser) where T : struct
{
    T result;
    if (parser(value, out result))
        return result;
    return null;
}

The struct constraint on T is required to align with the constraint on the Nullable<T> returned by the method.

We can now greatly simplify our efforts to parse nullable values:

var myIntPropStr = properties.BeforeProperties["MyIntProp"] as string;
var myIntProp = myPropStr.ParseWith<int>(int.TryParse);
if(myIntProp == null)
    throw new Exception("MyIntProp is empty!");

One quirk of this technique is that Visual Studio usually cannot infer T from just the TryParse method because of its multiple overloads. One option would be to write a dedicated method for each value type, but I would view this as unnecessary cluttering of the string type. Your mileage may vary.

Advertisements
Posted in .NET. Comments Off on Quick Tip: Parse String to Nullable Value
%d bloggers like this: