Scenario
Parse a string into a nullable numeric type. If the parse is unsuccessful, the result should be null; otherwise the result should be the parsed value.
Question
To accomplish this, I have always used the following simple but lengthily annoying method:
string numericString = "..."; decimal? numericValue; decimal temp; if (decimal.TryParse(numericString, out temp)) { numericValue = temp; } else { numericValue = null; }
I use the above method because the following doesn't compile:
decimal temp; decimal? numericValue = decimal.TryParse(numericString, out temp) ? temp : null;
Does anybody know of a version of the first bit of code that is as short, tidy, and readable as the second bit? I know I could always write an extension method that encapsulates the first bit of code, but I'm wondering if there is any way to do what I want without an extension method.
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?);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With