I am attempting to use Pre-compiler directives to toggle certain features in my application. I am using Pre-compiler directives as opposed to const static
variables because these features will not occur in the release version of the application.
Is it true that C# does not allow for all C Pre-compiler commands, ie, #if X > Y
& etc.? My below code is throwing compiler errors. Is it possible to use Pre-compiler directives to toggle functionality in my application?
My solution is a very 'C++/C' way of achieving this functionality. What is the C# way of achieving this functionality?
#define DEBUG 1 // Not allowed to assign values to constants?
#define USE_ALTERNATE_METHOD 0
public class MyApplication
{
public MyApplication()
{
#if DBEUG > 0 // Not allowed these kinds of directives?
RegressionTests.Run();
#endif // DEBUG > 0
}
public void myMethod
{
#if USE_ALTERNATE_METHOD > 0
// Do alternate stuff
#else
// Do regular stuff
#endif // USE_ALTERNATE_METHOD > 0
}
}
Specifying just #if DEBUG
does the work.
You cannot use pre-processor definitives like #define DEBUG 1
.
However you can just specify #define DEBUG
or #define CustomDefinition
and use it with the Conditional
attribute.
Eg,
You can just do this:
#if DEBUG
Console.WriteLine("This will work in DEBUG mode alone");
#endif
Or you can specify conditional-attributes
on top of the method that you wanna execute only in the debug mode.
Eg,
[Conditional("DEBUG")]
void ExecuteOnlyInDebugMode()
{
// do stuff you wanna do.
}
For your example it has to be like this:
#define DEBUG
#define USE_ALTERNATE_METHOD
public class MyApplication
{
public MyApplication()
{
#if DEBUG
RegressionTests.Run();
#endif
}
public void myMethod
{
#if USE_ALTERNATE_METHOD
// Do alternate stuff
//do not execute the following. just return.
#endif
// Do regular stuff
}
}
You can find more info here . Beautifully explained.
Also, read more that Conditional
attribute, here.