33

Please note that the question isn't about negating a boolean value but rather about the most elegant, efficient and nicest way of doing so.

Upon a click on a toggle button, I execute the following code to store the new state in a private bool.

_isIt = !_isIt;

It works, sure. It's readable, sure. But so is i = i + 1, still, we always write i++. Is there a neater way to toggle a bool?

9
  • 5
    Is there a problem with what you have now? If not, then you don't have a problem... Oct 5, 2012 at 17:29
  • 2
    @carlosfigueira It's not a problem of the kind "it's not working". It's rather an issue of type "can it be done better".
    – user1675891
    Oct 5, 2012 at 17:30
  • 2
    I suppose you could make a Toggle() extension method if you think that would be more identifiable in your code. It's completely superfluous though.
    – BZink
    Oct 5, 2012 at 17:32
  • If you're asking about whether there's something like _isIt !=, then no, it can't be done better. Oct 5, 2012 at 17:33
  • 1
    @carlosfigueira Exactly. Something like _isIt!!; would be great. This exact syntax doesn't work, of course, but I was hoping for something else, like that. If there's not such a thing (which seems to be the general concesus) I guess, I'm satisfied and happy. Thanks!
    – user1675891
    Oct 5, 2012 at 17:35

5 Answers 5

27

In fact there is another option to toggle a boolean value, this will work:

_isIt ^= true;

However this is not better than the way you did...

5
  • 4
    Haha, +1 for creativity. And you're perfectly right - it's not better. :)
    – user1675891
    Oct 5, 2012 at 17:36
  • 4
    I disagree - it's much more readable than: this.VerbosePropertyName.VerboseMemberClass.SomeSetting = !this.VerbosePropertyName.VerboseMemberClass.SomeSetting;
    – decPL
    Nov 7, 2013 at 13:48
  • @decPL, but maybe this.ToggleVerbosePropertyName() is better ;) Aug 6, 2014 at 14:36
  • 1
    I agree - maybe - we can't really say without some more context. As a rule of thumb in all the places I've worked, we'd prefer someProp ^= true as much cleaner than having a separate descriptive method for such a trivial operation (in the same way i++ is much better than say MathematicalUtils.IncreaseNumeric(ref i)), but obviously YMMV.
    – decPL
    Aug 7, 2014 at 7:25
  • 1
    I like this solution because I was able to simplify toggling a checkbox like this: ((CheckBox)((DockPanel)sender).Children[0]).IsChecked ^= true;
    – Sean
    Apr 26, 2018 at 19:01
20

No. That's the optimal way. Congratulations!

Even IF there would be an other way (as you commented - _isIt!!), I believe that it would be better not to use it because you'd be raising a lot of eyebrows anyway.

4

A Quick Note

Though an answer has been accepted, I believe a more in-depth answer would be nice for future readers to have. As this post has pointed out, the ! or NOT operator is the most widely accepted, and the optimal solution. In fact, when compared to ^ or XOR over 10,000 iterations it is roughly 100ms faster. The usage all depends on the circumstance to be honest. Either way, below you will find the three most common methods of toggling a bool value, and you should choose what you are most comfortable with using, within the standards you're allowed to use.


The if-else Method

The easiest way to toggle a bool value is to write out an if-else that assigns the new value; this way even a complete beginner to development can understand what is going on. This is actually how toggling is taught in most conceptual classes.

bool b = true;
if (b == true)
    b = false;
else
    b = true;

Of course the if can be simplified to if (b), but traditionally, you'll write it all the way out for clarity and learning purposes.


The NOT Operator

As you learn more about development and logical operations, you'll learn about the NOT operator or ! in C#. The usage of this operator is the most widely accepted in the industry for multiple reasons. It's simple, it's easy to read, it's easy to understand, and it's fast:

x = !x;

This breaks down to !true = false and !false = true.


The XOR Operator

The XOR or ^ in C# is the less-chosen operator for this task, but it is an acceptable operator depending on the situation. As some have pointed out in comments, this operator is especially useful when dealing with longer names or deep-access members. If performance matters, and the operation will be executed multiple times, it's best to go with the NOT operator, as it is faster. If performance isn't really a concern, then using the XOR operator is acceptable; though in a professional environment you'll likely need to justify the usage.

b ^= true;
b = b ^ true;

The biggest thing to understand about XOR prior to using it for a toggle, is understanding how it works logically:

true ^ false = true;
true ^ true = false;
false ^ true = true;
false ^ false = false;

That logic table explains why b ^= false won't toggle. A XOR requires one side of the operator to be true and the other to be false. Which side it is doesn't matter, but neither side can be the same value or it will evaluate to false. Hence:

bool b = true;
b ^= false; // true.
b ^= false; // true. So on, and so forth.

bool b = false;
b ^= false; // false.
b ^= false; // false. So on, and so forth.

Final Thoughts

The answer to the OP's question is simply:

  • The NOT operator is the cleanest and most efficient solution for toggling.

I wish you all the best of luck in your future endeavors, and hopefully this answer helped to shed further light on the topic!

2
  • What do you mean by x != x in your explanation? You're not implying that is equivalent to x = !x, are you? Oct 16, 2020 at 20:26
  • 1
    No, that was a copypasta from my code that I forgot to remove. Thanks for pointing that out! Oct 19, 2020 at 20:11
3

No, I believe that is the idiomatic C# way of toggling a bool (i.e. assigning it the opposite value).

My opinion: Keep your code as it is. It clearly conveys the intent of the code, which is the most important thing for future readers.

If you are interested in alternative ways of doing it, you could use XOR, but I will argue it is less readable.

_isIt ^= true;
0

No, there isn't. I don't know what else to add to this answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.