C# – How to Use Ternary Operators in C#

.netc++methodsternary-operator

With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int:

int x = (x == y) ? Func1() : Func2();

However, is there any way to do the same thing, without returning a value? For example, something like (assuming Func1() and Func2() return void):

(x == y) ? Func1() : Func2();

I realise this could be accomplished using an if statement, I just wondered if there was a way to do it like this.

Best Answer

Weird, but you could do

class Program
{
    private delegate void F();

    static void Main(string[] args)
    {
        ((1 == 1) ? new F(f1) : new F(f2))();
    }

    static void f1()
    {
        Console.WriteLine("1");
    }

    static void f2()
    { 
        Console.WriteLine("2");
    }
}
Related Question