Wednesday 15 July 2015

Segregating Debug Code with Release Code

Hi everyone,

This post will teach you how to segregate debug code with final/release code.

DEBUG pre-processor directive will tell compiler to which code portion should be run for different debug or build options.

#if DEBUG
    // Code should be executed when Debug mode is chosen
#else
    // Code should be executed when Release mode is selected
#endif

One thing that you make sure is DEBUG defined constant option is checked under PROJECT PROPERTIES > BUILD PAGE, as shown below


You can see in below images: when DEBUG option is enable code (left image) within IF condition highlighted and vice versa when this option is disabled (right image).

 

For Methods, you can also use CONDITIONAL attribute. 


With attributes defined, method can be called as normal in Debug mode.


With attributes defined, method can't be called (ignored by compiler) in Release mode.



There are two main advantages of using Conditional attribute over pre-processor directive #if:
  1. Your code in both cases either debug or release is being verified by compiler.
  2. In release mode, Method with conditional Debug attributed will not be automatically called.

Note: Conditional attribute can only be applicable on method with void return type.

You can also use .NET's Debug Class. Sample code is give below:


1 comment: