Link Search Menu Expand Document

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


In this video, we’ll be going to learn that how we can conditionally execute the method using Conditional attribute resided in the “System.Diagnostics” namespace depending on the predefined compilation symbol. Conditional attribute tells the compiler that whenever a method is called which contains this attribute, and if the passing symbol is defined, then include the call to the method. But if the symbol isn’t defined, then the call to the method will be removed from the compiled assembly.

In this application, I once again initialize an instance of this log API class. One thing to notice here is that we have removed all the ‘if’ preprocessor directives from this code. Open this class, now to conditionally execute this method based on the compilation symbol we need to add a conditional attribute.

Conditional Attribute

But before that, to support that conditional attribute, I need to add one namespace, which is (System.Diagnostics) and then I need to define the conditional attribute. In the parameter, I need to specify the symbol name which is ‘sandbox’.

Conditional Attribute C Sharp

After executing this application, we are able to log all the messages in this console. Remove that compilation symbol (sandbox) from this application. Open the property window of this application. Go to the Bill section and remove the symbol. When I run this application again, the messages are not displayed in the console.

This conditional attribute tells the compiler that whenever this method is called and if the sandboxing symbol is defined, then include the call to this method. If the symbol is not defined, then calls to the method will be removed from the compiled assembly.

For more videos and articles visit:

👉 GET YOUR FREE API KEY for PDF.co

https://app.pdf.co/signup?utm_source=youtube

✅ ON-PREMISE SDK FREE TRIAL:

https://bytescout.com/download/web-installer?utm_source=youtube

🔎 SDK DOCUMENTATION:

https://bytescout.com/documentation/

🔑 WEB API DOCUMENTATION :

https://pdf.co/rest-web-api