for (int i = 0; i < 10; ++i)
            {
                i > 5 ? MethodA(i) : MethodB(i);
            }

When trying to do the above I get this error

Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'

Does this mean there is no chance of doing the above with a ternary operator?

Recommended Answers

All 3 Replies

The Ternary or conditional operator returns one of two values depending on the value of a Boolean expression.

Specify the return type of your methods.

static void Main()
    {
        for (int i = 0; i < 10; ++i)
        {
            int j=i > 5 ? MethodA(i) : MethodB(i);
        }
    }
    static int  MethodA(int i)
    {
        return 0;
    }
    static int  MethodB(int i)
    {
        return 1;
    }

You do not know the proper definition of that operator.
The syntax:
boolean_expression ? expression1 : expression2
Expression is any operation which returns a value. Void is not a value. Void specifies that no value is returned. If your get this message, at least one of your methods, must return void value. What is more you must in that context assign the value returned by the "?:" operator.
Proper usage of that operator:

private int m1(int a)
        {
            return a;
        }
        private int m2(int a)
        {
            return a + a;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int j = 0;
            for (int i = 0; i < 10; i++)
            {
                j = (i > 5) ? m1(i) : m2(i);
            }
        }

If you don't want to use a value returned by the operator - you just want to decide which method to execute, use if - else or switch - case expressions.

commented: Well explained. +6

Thank you :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.