Patrick Bader's Blog a blog about software development

18Apr/111

Negating Booleans in C#

I was recently asked whether there is a short way to negate the value of a boolean variable. Surely you can simply asign the result of the negated variable to itself:

bool a;
[...]
a = !a;

So what is the problem here? Absolutely nothing of course. But now think of some common use case, for example in UI code:

MyForm.MyCheckbox.Checked = !MyForm.MyCheckbox.Checked;

Now, can you think of a way in C# to only write the variable name once?

There is indeed a way using compound assignment operators. The following code does the negation:

MyForm.MyCheckbox.Checked ^= true;

Well, I admit that this is not the clearest solution to the problem of negation, but it surely solves it. There is also an advantage or difference between this code and the initial. In the initial code "MyForm.MyCheckbox.Checked" will be evaluated twice and in the latter only once. Eric Lippert already wrote about this in his Blog.
Whether you will be using this obscure syntax or not is up to you. I for myself favour code where the intentions of the author are obvious which clearly is not the case here.

Comments (1) Trackbacks (0)
  1. Oh my.. Suddenly I feel much less concerned about the extra work to write
    bla = not bla
    Should never have raised that topic! 😀

    Well lucky, there is no xor-assign operator in VB.Net, as – who wonders – xor is verbose:
    bytes = bytes Xor mask

    … Now I do feel jealous and lucky at the same time!


Leave a comment

No trackbacks yet.