Reputation: 2504
As I understand statements like Debug.WriteLine()
will not stay in the code in the Release build. On the other hand Trace.WriteLine()
will stay in the code in the Release build.
What is controling this behaviour? Does the C# compiler ignores everything from the System.Diagnostics.Debug
class when the DEBUG
is defined?
I am just trying to understand the internals of C# and just curious.
Upvotes: 10
Views: 3650
Reputation: 1062492
This is due to ConditionalAttribute
; the compiler ignores calls to methods marked as conditional unless that symbol is defined.
You can have your own:
[Conditional("BLUE")]
void Bar() {...}
which will only be called when BLUE is defined.
Note that there are some restrictions, to make "definite assignment" work:
(the same restrictions apply to partial
methods for similar reasons)
Upvotes: 5
Reputation: 62367
These methods use the ConditionalAttribute
to designate when they should be included.
When DEBUG
is specified as a #define
, via the command line or the system environment (set DEBUG = 1
in the shell), a method marked with [Conditional("DEBUG")]
will be included by the compiler. When DEBUG
is not included, those methods and any calls to them will be omitted. You can use this mechanism yourself to include methods under certain circumstances and it is also used to control the Trace
calls like Trace.WriteLine
(this uses the TRACE
define).
Upvotes: 6