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?
The reason why the above statement does not work was provided by the other users and effectively did not answer my true question.
After playing around some more, I figured out that you CAN use this operator to do the above statement, but it results in some bad code.
If I were to change the above statement to;
This code will compile and execute the way it should. However, if these methods were not originally intended to return anything, and referenced other areas in the code, you now have to handle a return object each time to call these methods.
Otherwise, you now can use a ternary operator for a one-line method chooser and even know which method it called in the next line using the result.
Now, this code is absolutely pointless and could be easily done by a If Else, but I just wanted to know if it could be done, and what you had to do to get it to work.
Now that I know that you can effectively return any type in these methods, this might become a little more useful. It may be considered a “Bad Coding Practice” but might become very useful in situations it was never MEANT for.
You could get access to one object or another based on any condition and that might be very useful in one line of code.
Sure, this can be done by an If Statement, but I think that using the Ternary Operator for other uses makes programming fun. Now, this may not be as efficient as an If Else statement, in which case, I would never use this.