Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A conditional attribute is a tag used to mark a method or class whose execution depends on the definition of preprocessing identifier.
A conditional attribute indicates a condition to specify conditional compilation wherein methods are selectively called on the basis of definition of symbols. It instructs the compiler to compile (into Microsoft Intermediate Language) or not compile specific blocks of code, based on a condition - whether or not a specific conditional compilation symbol is defined. If specific symbols have not been defined at the instant they are called, then calls to that method or class will be ignored by the compiler.
A conditional attribute has the following characteristics:
A conditional attribute provides a declarative programming pattern and helps to easily maintain source code. By applying a conditional attribute at the method level, source code is more readable. The caller of a method need not take additional code for conditional compilation. A conditional attribute is used to enable tracing and logging functionalities in the debug builds by using the identifier DEBUG to display and log diagnostic information related to the application. Also, it helps to separate logic related to the debug build (in systems used for development) from release builds, which are deployed in sites and applications. To maintain multiple editions (with selected features in some edition) of a software without code duplication, conditional compilation forms the right technique by which the single main source code is maintained for multiple editions based on the respective symbols defined for them.
Following are few rules to follow while using a conditional attribute:
Although usage of "#if and #endif" forms an alternate option to conditional attribute, the latter provides a more clean, elegant and less error-prone approach when compared to the former. Internally, the difference is that while using a conditional attribute for a method, method will still be a part of the assembly and not loaded. But in the case of #if / #endif, method will not be visible in the assembly itself.