? operator without else part

I use C# ? operator when I have if-statements that affects one row and it's all good. But lets say I have this code (using classic if-statements):

if(someStatement)
{
    someBool = true;  //someBools value is unknown
}
else
{
    //Do nothing
}

This can be achieved on a one-liner by doing:

someBool = (someStatement) ? true : someBool;

But why can't I do something like this:

someBool = (someStatement) ? true : ;
//or possibly
someBool = (someStatement) ? true;

Is this possible in some way? If it is, is there any benefits of using one method over the other? And if not, why shouldn't you be able to do it?

Jon Skeet
people
quotationmark

Basically, you're trying to use the conditional operator for something that it's not designed for.

It's not meant to optionally take some action... it's meant to evaluate one expression or another, and that be the result of the expression.

If you only want to perform an action when some condition is met, use an if statement - that's precisely what it's there for.

In your example, you could use:

// Renamed someStatement to someCondition for clarity
someBool |= someCondition;

or

someBool = someCondition ? true : someBool;

... in other words "use the existing value unless someCondition is true... but personally, I think the original if statement is clearer.

people

See more on this question at Stackoverflow