how can I convert this simple if statement into :? (ternary) operator in C#?
case "amount": { if(!Decimal.TryParse( fvm.Value,out a)) a=Decimal.MinValue; break; }
how can I convert this simple if statement into :? (ternary) operator in C#?
case "amount": { if(!Decimal.TryParse( fvm.Value,out a)) a=Decimal.MinValue; break; }
You can either assign the value of a
back to itself on success, or use a separate temporary variable (I'd prefer the latter):
case: "amount":
a = decimal.TryParse(fvm.Value, out var tmp) ? tmp : decimal.MinValue;
break;
a = Decimal.TryParse( fvm.Value,out var tmp) ? tmp : Decimal.MinValue;
break;
I would personally prefer to create an helper method
public static decimal? ParseDecimal(string str) => Decimal.TryParse(str, out var tmp) ? (decimal?)tmp : null;
since that would let you use the null-coalescing operator:
a = ParceDecimal(fvm.Value) ?? decimal.MinValue