adopilot
adopilot

Reputation: 4500

Easy way to change value of boolean

I often have inverse logic between my forms and data. I am looking for the easiest (most elegant) way to change some boolean from true to false and vice versa.
I know that a lot of people will get angry if they see code like this:

if (c)
{
    return false;
}
else
{
    return true;
}

Or something like this:

EDIT:

I am sorry, my code sample is not good.
How do I find the inverse value of a boolean in a more elegant way?

myMethod(!op.checkBoxSamoSaKol.Checked) // Is this possibile

Upvotes: 0

Views: 3457

Answers (3)

Anindya Chatterjee
Anindya Chatterjee

Reputation: 5964

The best possible expression would be (as Øyvind Bråthen) suggested as follows

return !CheckBoxOnContolOnForm.Checked;

Upvotes: 0

Paul Ruane
Paul Ruane

Reputation: 38590

I think you'll find that is called the 'not' operator.

return !CheckBoxOnContolOnForm.Checked;

Upvotes: 11

Øyvind Bråthen
Øyvind Bråthen

Reputation: 60694

If you want to return, just do it like this

return CheckBoxOnContolOnForm.Checked;

If you want to invert a boolean value, the simplest is this syntax:

myBool = !myBool;

EDIT

In your case I see you want to return false if it's checked. In that case it should be written like this:

return !CheckBoxOnContolOnForm.Checked;

Upvotes: 4

Related Questions