C# – Method Call Using Ternary Operator

c++conditional-operator

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?

Best Answer

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.

Related Question