M
Michael A. Covington
Is there a quick way to toggle a Boolean variable? Something shorter than:
blah.blither.blatt = ! blah.blither.blatt;
blah.blither.blatt = ! blah.blither.blatt;
Is there a quick way to toggle a Boolean variable? Something
shorter than:
blah.blither.blatt = ! blah.blither.blatt;
Michael A. Covington said:Is there a quick way to toggle a Boolean variable? Something shorter than:
blah.blither.blatt = ! blah.blither.blatt;
Michael A. Covington said:Found it. I can write:
blah.blither.blatt ^= true;
which flips the Boolean value, because it is equivalent to:
blah.blither.blatt = blah.blither.blatt ^ true;
where ^ is xor.
Jon Skeet said:While I'm sure you're right about it working, I don't think that's an
argument to use it - at least not if you think anyone else is going to
read your code. Even though it's fewer characters than
blah.blither.blatt = !blah.blither.blatt;
I would suggest that most people would find the latter far
easier/quicker to understand - and code generally spends more time in
maintenance than being written.
Of course, if this is all just an academic exercise for interest's
sake, that's a different matter.
couldn't you override an operator to do what you want.
and create a unary boolean switch?
so, in the way the increment operator is +=
the boolean flip would be !,
so
myBool = false;
!myBool;
Console.WriteLine(myBool.ToString);