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.
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.
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.
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 .
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");
}
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With