Home > Mobile >  C#: Can you apply the ternary conditional operator (?:) to statements?
C#: Can you apply the ternary conditional operator (?:) to statements?

Time:11-01

I love C#'s ability to return an expression using the ternary conditional operator. But I would like to execute a statement as opposed to merely returning an expression using a ternary conditional-like procedure; is there a way to do this?

//TRADITIONAL TERNARY CONDITIONAL (i.e., ?:):
a = isBob ? "Bob" : "Steve";

//HOW YOU WOULD WRITE MY PROPOSITION TRADITIONALLY:
if (isBob) { a = "Bob"; } else { b = "Steve"; }

//GOAL — HOW YOU WOULD LIKELY WRITE MY PROPOSITION USING THIS PROPOSED OPERATOR (e.g., !?!?):
isBob !?!? a = "Bob" : b = "Steve";

Is this possible, or is it just wishful thinking? I am guessing it may be the latter, but I just wanted to make sure by first checking with C# veterans. Thank you!

CodePudding user response:

You can write this if you like, assuming you're getting mixed up between null coalescing and ternary

_ = isBob ? a = "Bob" : b = "Steve";

This will test the boolean isBob, and if true it will assign "Bob" to string a and return the result of the assignment into the discard (ie throw it away), similar for b if isBob is false. You have to do something with a ternary's value, but discarding it is an acceptable something..

It's unusual, and a bit more limited than a standard if/else (the true/false parts of the ternary would have to be same type or type-convertible between each other) or uglier (you could cast one of the assignment results to object, ugh)

//euww, objecfuscation?
_ = isBob ? (object)(a = "Bob") : b = 1;

//it's not so bad
if(isBob) a = "Bob"; else b= "Steve";
  •  Tags:  
  • c#
  • Related