What are some examples of how to use #define in C#?
#define //preprocessor directive
What is the purpose of it? Here is an example from Microsoft which I still don’t get:
// preprocessor_if.cs
#define DEBUG
#define MYTEST
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !MYTEST)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && MYTEST)
Console.WriteLine("MYTEST is defined");
#elif (DEBUG && MYTEST)
Console.WriteLine("DEBUG and MYTEST are defined");
#else
Console.WriteLine("DEBUG and MYTEST are not defined");
#endif
}
}
Quote:
and
and
In your example, if
DEBUGis defined (does not matter what it is as long as it is defined) and MYTEST is not defined, then it will show the message shown.Otherwise, if
DEBUGis not defined but MYTEST is defined, then it will show the message shown.If both are defined then it will show the message shown.
Bottom-line:
The point of the defines is to selectively apply compilation options to your program to give it a different program flow. It is a carryover from C and C++.