Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Super-Easy Code Block Toggling

4.79/5 (37 votes)
22 Aug 2011CPOL 62.6K  
If you have two blocks of code that you are testing and need to switch back-and-forth between them, here's a commenting trick that works as a powerful code block toggling mechanism.Say you have a variable called foo of type string and want to change between using initialized values and...
If you have two blocks of code that you are testing and need to switch back-and-forth between them, here's a commenting trick that works as a powerful code block toggling mechanism.

Say you have a variable called foo of type string and want to change between using initialized values and non-initialized values for quick testing or more likely, because your boss asked you to. Silly boss!

C#
//*
string foo = string.Empty;
/*/
string foo = "initialized";
//*/
foo += "bar";


Now, to toggle the section that is 'live', simply remove the first slash from the first line comment, as follows:

C#
/*
string foo = string.Empty;
/*/
string foo = "initialized";
//*/
foo += "bar";


Obviously, for a simple string there are easier ways to do this, but this is sure handy for more complex object setup.

There you go! With one keystroke you totally own on switching between two blocks of code.

While #ifdef works in some scenarios this technique also works in non-compiled languages such as JavaScript.

Cheers!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)