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?
If Else
, just write it as one line:if (condition) doThis(); else doThat();
Granted, the ternary operator (if it worked the way you thought) would be shorter, but terseness isn't always a good thing. – Spoilsman