Parse string into nullable numeric type (1 or 2 liner)

I'd do something like this:

public delegate bool TryParseDelegate<T>(string str, out T value);

public static T? TryParseOrNull<T>(TryParseDelegate<T> parse, string str) where T : struct
{
    T value;
    return parse(str, out value) ? value : (T?)null;
}

decimal? numericValue = TryParseOrNull<decimal>(decimal.TryParse, numericString);

Or you could make it an extension method:

public static T? TryParseAs<T>(this string str, TryParseDelegate<T> parse) where T : struct
{
    T value;
    return parse(str, out value) ? value : (T?)null;
}

decimal? numericValue = numericString.TryParseAs<decimal>(decimal.TryParse);

One simple explicit typecast makes it compilable:

decimal temp;
// typecast either 'temp' or 'null'
decimal? numericValue =
  decimal.TryParse(numericString, out temp) ? temp : (decimal?)null;

Another option is to use the default operator on the desired nullable type:

decimal temp;
// replace null with default
decimal? numericValue =
  decimal.TryParse(numericString, out temp) ? temp : default(decimal?);

Tags:

C#

.Net