'Is a ternary expression possible for this construct?
I'm not sure if the following statement is possible to write as one line (i.e., ternary form).
if (A == B)
FunctionA();
else
FunctionB();
Both FunctionA and FunctionB are type void.
Solution 1:[1]
if the following statement is possible to write as one line
Sure:
if (A == B) FunctionA(); else FunctionB();
Solution 2:[2]
No, use the if statement.
However, by casting the two void functions to Action, this hack is possible:
(A == B ? (Action)FunctionA : FunctionB).Invoke();
This is especially handy when used in expression body => methods because if can't be used there.
Of course: don't do that in serious projects!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henk Holterman |
| Solution 2 |
