Marks a conditional method, a method whose execution depends on a specified pre-processing identifier.
[conditional(conditionalSymbol)]
Method declarations.
The conditional attribute is a multi-use attribute. conditional is an alias for System.Diagnostics.ConditionalAttribute.
Wherever a conditional method is called, the presence or absence of the preprocessing symbol specified by conditionalSymbol at the point of the call determines whether the call is included or omitted. If the symbol is defined, the call is included, otherwise the call is omitted. Conditional methods provide a cleaner, more elegant alternative to enclosing the method call in #if conditionalSymbol...#endif preprocessor directives.
A conditional method must be a method in a class or struct declaration and must have a return type of void (for other restrictions, see 17.4.4 conditional).
If a method has multiple conditional attributes, a call to the method is included if at least one of the conditional symbols is defined (in other words, the symbols are logically ORed together).
[conditional("A"), conditional("B")] public static void IfAorB() {...}
To achieve the effect of logically ANDing symbols, you can define serial conditional methods:
[conditional("A")] public static void IfAandB() { AandBPrivate(); } [conditional("B")] static void AandBPrivate() { /* code to execute when both A and B are defined... */ }
Call IfAandB
; if both A
and B
are defined, AandBPrivate
will execute.
#define DEBUG using System; public class Trace { [conditional("DEBUG")] public static void Msg(string msg) { Console.WriteLine(msg); } } class Test { static void A() { Trace.Msg("now in A."); B(); } static void B() { Trace.Msg("now in B."); } public static void Main() { Trace.Msg("now in Main."); A(); Console.WriteLine("done."); } }
now in Main. now in A. now in B. done.
Same as above, but with first line changed to
#undef DEBUG
done.