<!-- Article Starts - DO NOT ADD HTML/BODY START TAGS-->
Conditional Methods using Conditional Attribute
Conditional Attribute is defined in System.Diagnostics namespace.
When a conditional method is called its call is determined by the presence or absence of the preprocessor symbol used with the conditional attribute. If this preprocessor symbol is defined then the mehotd call is included else omitted.
Using conditional attibute is an alternative to calling methods in #if & #endif preprocessors.
A method can have multiple conditional attributes. The call to such a method is made if at least one of the conditional symbols is defined.
A conditional method has a few constraints:
- A conditional method must be a method in a class or struct declaration and should not have any return type ... i.e. the return type should be "void".
- The conditional method must be a method in a class or struct declaration a compile-time error occurs if the Conditional attribute is specified on a method in an interface declaration.
- Conditional methods cannot be marked with override keyword.
- Conditional methods can be virtual and the methods which override such a conditional method implicitly becomes Conditional
- Methods defined in an interface cannot be marked as conditional.
1. Create a new Console Application and define 2 classes MyClass and MyClient.
2. In MyClass define two as shown below.
<FONT color=#0000ff><FONT face=Arial>class MyClass
3. In MyClient write the preprocessor directives as shown . (They should be the first two lines in the file... above using System ... if not it will not compile)
4. Call the My Class methods from the main as shown
<FONT color=#0000ff><FONT face=Arial>public class MyClient
4. Build the solution and run . You will see both "Namratha" & "Nasha" ... i.e both the functions were called.
5. Now change the #define CON_Attrib1 to #undef CON_Attrib1. ... i.e. undefining the attribute.
6. Build the solution and run . You will see only "Nasha" ... i.e MyFun1 was not called as the preprocosser directive "CON_Attrib1" is not defined. But MyFun2 is called coz the other preprocessor directive "CON_Attrib2" is defined. When there are moer than one directives it an OR condition hence if any of the preprocessor directive is define the function will be called.
7. MyFun2 is marked as virtual hence if another function overrides its then is becomes conditional implicitly.
Let's keep things Simple .....