C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Argument: The string argument is the text of the symbol that must be defined for the method to be compiled.
Note: At the top of the program, you can see 2 preprocessor directives. The symbol PERLS is defined. The symbol DOT is not.
Note 2: The execution of the program shows that MethodA is executed, but MethodB is not.
Warning: It isn't possible to use Conditional on methods that return a value. Methods must be used in the void context.
VoidAnd: This is because variables can be assigned to method return values. You can work around this limitation using parameters.
C# program that uses Conditional attribute
#define PERLS
#undef DOT
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
MethodA();
MethodB();
}
[Conditional("PERLS")]
static void MethodA()
{
Console.WriteLine(true);
}
[Conditional("DOT")]
static void MethodB()
{
Console.WriteLine(false);
}
}
Output
True
Tip: You can use clunky #if and #endif directives all over your code, but this is an eyesore and also prone to typos.
DirectivesAddToArray: It defines an AddToArray method, which simply adds two elements to the array. It uses the Conditional("DEBUG") attribute.
Info: This means to only compile the method if DEBUG is defined. The Conditional attribute requires System.Diagnostics.
C# program that uses conditional method
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Program
{
static void Main()
{
List<string> l = new List<string>();
l.Add("rabbit");
l.Add("bird");
AddToArray(l);
Console.WriteLine("Elements: {0}", l.Count);
Console.Read();
}
[Conditional("DEBUG")]
static void AddToArray(List<string> l)
{
// New array
string[] a = new string[2];
a[0] = "cat";
a[1] = "mouse";
// Add array to end of list
l.AddRange(a);
}
}
Output of the program in DEBUG
Elements: 4
Output of the program in RELEASE
Elements: 2
Note: In the example, Main() doesn't know "cat" and "mouse" even exist. This clarifies the code.
Note: This syntax is more high-level, less lexical. It is a declarative programming pattern.
Thus: The Conditional attribute helps maintain descriptive and easy-to-maintain source code.