While playing around with new concepts, I came across the Ternary Operator
and its beauty. After playing with it for a while, I decided to test its limits.
However, my fun was ended quickly when I couldn't get a certain line of code to compile.
int a = 5; int b = 10; a == b ? doThis() : doThat() private void doThis() { MessageBox.Show("Did this"); } private void doThat() { MessageBox.Show("Did that"); }
This line gives me two errors:
Error 1 Only assignment, call, increment, decrement, and new object expressions can be used as a statement Error 2 Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'
I have never used a Ternary Operator
to decide which method to be called, nor do I know if it is even possible. I just like the idea of a one-line If Else Statement
for method calling.
I have done a bit of research and I cannot find any examples of anyone doing this, so I think I might be hoping for something impossible.
If this is possible, please enlighten me in my wrong doings, and it isn't possible, is there another way?
Nope, you can only assign values when doing ternary operations, not execute functions.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Example: C Ternary Operator Here, age >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.
The ternary operator is a common tool that you'll see a lot in JavaScript code. It can make your code concise but it can also make your code unreadable if you don't use it properly. Try to keep the ternaries simple and readable.
The ternary operator is used to return values and those values must be assigned. Assuming that the methods doThis()
and doThat()
return values, a simple assignment will fix your problem.
If you want to do what you are trying, it is possible, but the solution isn't pretty.
int a = 5; int b = 10; (a == b ? (Action)doThis : doThat)();
This returns an Action delegate which is then invoked by the parenthesis. This is not a typical way to achieve this.
Ternary operator must return something. A typical usage is like this:
int x = (a > b) ? a : b;
If you try something like
a + b;
The compiler will complain.
(a > b) ? a - b : b - a;
is basically a shortcut for either "a - b" or "b - a", which are not legitimate statements on their own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With