Blog VS 2010 All Tutorials Wordpress Studio
Certification LinksRandom Thoughts

Code Gallery

We are putting together a group of examples from our personal libraries our favorite bits of ‘useful’ code. This isn’t ground breaking stuff but it’s the kind of code you either use over and over and really want have around.

Something like this…

The famous value toggle


All programmers will eventually use some type of boolean value to determine the next step in the logic. After using this boolean value, the most common step is to then turn the value either off / on (false / true).

Here’s an example of using a boolean like a toggle or off / on switch.

//boolean variable to be used.
bool bAnswer = false;
//do some action – user input – test a value etc. and then evaluate
if(bAnswer == true);
   bAnswer = false;
else
   bAnswer = true;

Okay, so that worked. Easy enough to understand. If true, make false. If false, make true. But look at the simple one liner that can easily replace this logic and will always produce the toggle (true/false | 1/0 | on/off)

bAnswer = !bAnswer; (remember that the “!” sign means “NOT”)

That’s it. It takes a minute to get your head around it but then it makes all the sense in the world. What you’re saying is that there are only 2 values (in this case true or false). So if it is one value and you want to change it to the other available value then just set it to the opposite.

In English…

true is not (“!”) true (that means it’s now false)
false is not (“!”) false (now it’s true)


No matter what it is, it will always be the opposite value once it processes.

This belongs in the categories of:
Easy, Safe, and Best Practice.