Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

No. The conditional operator is only valid for non-void expressions. The point is to evaluate one of two expressions, and for that to be the result.

Basically: write the if statement. It's the idiomatic way of executing one action or another.

You could write an extension method like this:

// For demonstration purposes only. Please don't use in real life.
public static void Conditional(this bool result,
                               Action trueAction,
                               Action falseAction)
{
    Action action = result ? trueAction : falseAction;
    action();
}

Then:

(A == B).Conditional(FunctionA, FunctionB);

... but I'd strongly advise you not to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...