Re: Ternary Conditional Operators and Method Calls

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 08/31/04


Date: Tue, 31 Aug 2004 12:02:23 +0100

Rob Williams <RobWilliams@discussions.microsoft.com> wrote:
> The following code will not compile...
>
> public bool active = false;
> public void Activate(){}
> public void Deactivate(){}
> public void object_Activate(object sender, EventArgs e){
> (active)? Deactivate() : Activate();
> }

Indeed.
 
> the compiler gives the following error...
>
> "Only assignment, call, increment, decrement, and new object expressions can
> be used as a statement"
>
> Now the two statements here are both Calls? In which case this should
> compile according to the given message?

No, because the overall statement is not a call. Each part of it is,
but it isn't in itself.

You can't write

Deactivate() && Activate();

either.

> If I change the code to this....
>
> public bool active = false;
> public bool Activate(){
> return true;
> }
> public bool Deactivate(){
> return false;
> }
> public void object_Activate(object sender, EventArgs e){
> active = (active)? Deactivate() : Activate();
> }
>
> It compiles as I am now doing an assignment.
>
> Is this an intentional feature of the C# compiler? And if so what is
> the reasoning behind it? It doesn't matter hugely as it is easy
> enough to work around.

The idea of the ternary conditional operator isn't to allow code like
yours - it's to allow things like parameter passing and assignment.

A far more idiomatic (and IMO easier to read) way of writing your code
would be:

if (active)
{
    Deactivate();
}
else
{
    Activate();
}

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages