Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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.

like image 336
Dan Avatar asked Oct 01 '12 22:10

Dan


2 Answers

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?); 
like image 176
Ondrej Tucny Avatar answered Sep 19 '22 02:09

Ondrej Tucny


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); 
like image 23
Lee Avatar answered Sep 19 '22 02:09

Lee