Parse string into nullable numeric type (1 or 2 liner)
.net, c#
Solution
A nice one liner using more recent C# features would be:
var numericValue = decimal.TryParse(numericString, out var temp) ? temp : default(decimal?);
Problem
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.