Throw this away and read the example here: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx.
You're doing way too much fuss for simple value parsing.
سؤال
I have a set of methods which receive user input as strings and parse it to decimals, ints etc at the header of each method. So, I have same code repeated many times in every method, for instance:
public ..... CreateOrder(....., string rawSourceAmount)
{
decimal? sourceAmount2 = rawSourceAmount.
TryToDecimal(XUtils.DecimalFormat(2)); // extension method, wrapper of Decimal.TryParse, returns null if fails
if (sourceAmount2 == null)
throw new XBadSourceAmountException(
sourceSystem.Id, rawSourceAmount);
decimal sourceAmount = sourceAmount2.Value;
..........
}
Why I have sourceAmount2
and sourceAmount
? Because later in the method body I actively use sourceAmount, and I do not want each time to write sourceAmount.Value
. Is there any way to simplify this templated code?
So, the task is: I have string rawSourceAmount
. I need decimal sourceAmount
and a place to throw different exception. I do not need sourceAmount2
.
المحلول
Throw this away and read the example here: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx.
You're doing way too much fuss for simple value parsing.
نصائح أخرى
Then change your return type of TryToDecimal
method.Make it bool
and add a out parameter to your method,then you can check returning result directly,you don't need to define extra nullable variable:
decimal sourceAmount;
if(!rawSourceAmount.TryToDecimal(XUtils.DecimalFormat(2),out sourceAmont)
{
throw new XBadSourceAmountException(
sourceSystem.Id, rawSourceAmount);
}