What is the usage of #if DEBUG
pre-processor directive in C#? When must we use this?
In Debug mode:
#if DEBUG
System.Console.WriteLine("Debug version");
#endif
System.Console.WriteLine("Output");
Output as
Debug version
Output
In Release mode:
#if DEBUG
System.Console.WriteLine("Debug version");
#endif
System.Console.WriteLine("Output");
Output as
Output
read this: #if (C# Reference)
Usage: If you have a set of values to be tested in the debug mode and not in the release mode you can use #if DEBUG
You might feel more comfortable with the Conditional
attribute, which can be used to exclude entire methods, without needing to complicate the source with conditionals on the calling side:
[Conditional("DEBUG")]
void Foo()
{
}
Foo()
can be safely called in both debug and release - however in release mode, it would be a no-op.
You don't have to use it at all. The purpose of it is to have sections of code that only get compiled in debug mode. e.g. you might have some code that enabled a master user, that could pretend to be any other user in the system for testing and debug pruposes. You would not want that user enabled in the release code for security reasons so you waould wrap the relevent sections of code in #if DEBUG and they would be excluded from release code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With