Ternary Conditional Operators and Method Calls

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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();
}

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?

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.

Cheers

Rob
 
Rob Williams said:
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();
}
 
Hi,

I believe its intentional. But they could have added another error message
specific to this though.

IMHO ?: is not a complete replacement for if-else blocks. It is designed for
use with statements whose conditional section returns a value, which is
being used somehow, not as a method invocation source.

Your first example statement: (active)? Deactivate() : Activate();...
happens to invoke methods depending upon 'active''s value, which should
actually be represented by an if-else block.

Rakesh
 
Back
Top