Link Search Menu Expand Document

How to Conditionally Execute Method Based on Compilation Symbol in C# - Part 1

In this video, we’ll be going to learn that how we can conditionally execute any code or method depending on the predefined compilation symbol In C#. When the C# compiler encounters this symbol within #if directive, followed by an #endif directive, it executes the code between the directives.

Did you know that in #C, we can conditionally compile and execute methods depending on the compilations symbol? In this session, we’ll be going to learn how we can conditionally execute any code or method depending on the predefined compilation symbol. In this demo console application, first I have initialized an instance of the log API class. In this class, this is just one simple method that will write this message in the console.

After that, I have defined these preprocessor ‘if’ directives. When the #C compiler encounters this preprocessor ‘if’ directive followed by an ‘end if’ directive, it compiles the code between the directives only if the specified symbol is defined. Right now for this application, I do not define any symbols. When I run the application, this [logAPI.LogAPIMessage(“First API method call started”);] line should not be hit. So for confirmation, let me add the breakpoint over here.

Programmers Essentials

Now, when I run the application, this() line is not executed. When I click on the Continue Button, there is no message printed over here. Let’s define this compilation symbol for this application. To define the compilation symbol, you need to go first into the application property. Then in this bill section, you need to define the compilation symbol in the textbooks. In our case, it is a sandbox. Let me save the application.

When I run the application our breakpoint is hit. You can see the message in the console application. Let’s say if I have lots of this type of method and I want to wrap this method in this type of preprocessor ‘if’ directive, it can start to get a bit messy. If I ever wanted to change the name of this symbol, for example, from sandbox to dev involvement, then I would need to change it in multiple places. There is an alternative to using the conditional compilation directive.

For more videos and articles visit: