#169 – The if Statement Must Always Include a Boolean Expression

In C++, an if statement can use a conditional expression that resolves to a numeric value.  The statement following the if statement will execute when this expression resolves to any non-zero value.  This form of the if statement is not allowed in C#.

            uint leaves = CountLeavesInBackyard();

            // Works in C++, but is not allowed in C#
            if (leaves)

Since the if statement must use a boolean expression in C#, we’d rewrite the code as:

            if (leaves > 0)

#168 – Use if Statement to Conditionally Execute a Block of Code

You can use the if statement in C# to check the value of a boolean expression and execute a block of code only if the expression is true.

            if (userAge >= 50)
                Console.WriteLine("Hey, you should consider joining AARP!");

If the value of the userAge variable is greater than or equal to 50, the block of code will be executed.  If the age is less than 50, the block will not be executed and the program will continue with the first statement after the block of code.

#115 – Using #if, #else, #endif

When using the #if directive to conditionally compile code if a particular symbol is defined, you can also  using #else to conditionally compile code if the symbol is not defined.

Here’s an example:

    DoLotsOfLogging();   // To assist in debugging

#112 – Conditionally Compiling Code in Debug Builds

By default, the C# project wizard sets up every project to have two different build configurations–Debug and Release.

Debug builds (as compared with Release builds):

  • Create executables in \bin\Debug directory
  • Do not optimize code
  • Define the DEBUG symbol
  • Write out full debug info

You build your projects in the Debug configuration during development, for the best debugging experience.  Then, when your program is ready to ship, you build the Release configuration and ship that version.

You may want to include certain code in your program that you use only for debugging purposes–so you include it in only the Debug build.  You do this using the #if directive, checking the DEBUG variable.

 static void Main(string[] args)
     DoSomeLogging();   // Only do this in Debug build
    uint x = 0x1234;
    x &= 0x0020;

Code within the #if/#endif directives will not be included in the release build.