Ternary operators in C #

With the ternary operator, you can do something like the following (assuming Func1 () and Func2 () return int:

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

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

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

I understand that this can be achieved with an if statement, I was just wondering if there is a way to do it this way.

+7
methods c # ternary-operator
source share
4 answers

Strange 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"); } } 
+10
source share

I do not think so. As far as I remember, the ternary operator is used in the context of the expression , and not as an operator. The compiler must know the type of expression, and void not a type.

You can try to define a function for this:

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

And then you can call it like this:

 iif(x > y, Func1, Func2); 

But this does not make the code more understandable ...

+3
source share

If you feel confident, you will create a static method whose sole purpose is to absorb the expression and say "do it."

 public static class Extension { public static void Do(this Object x) { } } 

Thus, you can call the ternary operator and call the extension method on it.

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

Or, in an almost equivalent way, write a static method (if the class is limited when you want to use this "shortcut").

 private static void Do(object item){ } 

... and calling it that way

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

However, I highly recommend not using this โ€œshortcutโ€ for the same reasons that were already clear to the authors who were in front of me.

+1
source share

No, because the ternary operator is an expression, while void actions / functions are operators. You can force them to return object , but I think the if / else block will make it much clearer (i.e., Actions are performed for their side effects instead of their values).

0
source share

All Articles