Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operators in C#

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.

like image 730
Paul Michaels Avatar asked May 04 '10 12:05

Paul Michaels


People also ask

What are ternary operators in C with example?

It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.

Why ternary operator is used in C?

The programmers utilize the ternary operator in case of decision making when longer conditional statements like if and else exist. In simpler words, when we use an operator on three variables or operands, it is known as a Ternary Operator.

Which is ternary operator?

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool .


2 Answers

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");
    }
}
like image 164
Diego Pereyra Avatar answered Sep 23 '22 17:09

Diego Pereyra


I don't think so. As far as I remember, the ternary operator is used in an expression context and not as a statement. The compiler needs to know the type for the expression and void is not really a type.

You could try to define a function for this:

void iif(bool condition, Action a, Action b)
{
    if (condition) a(); else b();
}

And then you could call it like this:

iif(x > y, Func1, Func2);

But this does not really make your code any clearer...

like image 30
Daren Thomas Avatar answered Sep 25 '22 17:09

Daren Thomas