You cannot use a method with a return type of void in a triple expression this way. The end of the story.
To understand why this is so, remember what the ternary operator actually does - it evaluates as follows:
(condition ? [true value] : [false value])
This means the following code:
int x = a ? b : c;
Need to rewrite :
int x; if (a) { x = b; } else { x = c; }
The two above are logically identical.
So how does this work with a method with void as the return type?
// Does this make sense? int x = condition ? foo(s) : foo(i); // Or this? if (condition) { x = foo(s); } else { x = foo(i); }
It is clear that the foregoing is not legal.
However, the suggestions of others would otherwise be valid if only your foo overloads returned the value.
In other words, if your signatures looked like this:
object foo(string s); object foo(int i);
Then you can do it (you throw away the return value, but at least it will be compiled):
object o = condition ? foo(0) : foo("");
In any case, ol ' if / else is your best bet, in this case.
source share