-1

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; }
1
  • 4
    the question should be: why? Seems pretty simple and easy to understand IMHO. I´d just put everything on new lines though. Feb 15, 2021 at 8:51

2 Answers 2

3

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;
0
0
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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.