I have a chunk of code that frequently needs tracing information output so that clients can help debug the output – it’s very math oriented.
I definitely don’t want the tracing to be enabled in production for performance reasons, but having to comment it in and out frequently is becoming a hassle.
I’ve just setup the code like this…
using System.Diagnostics;
const bool TRACING_ENABLED = false;
//math math math....
Trace.WriteLineIf(TRACING_ENABLED, "Minimum Nitrogen Yield: " + minYieldNitrogen);
Trace.WriteLineIf(TRACING_ENABLED, "Minimum Water Yield: " + minYieldWater);
Trace.WriteLineIf(TRACING_ENABLED, "Minimum Seed Yield: " + minYieldSeed);
//more math math trace math trace math...
My question is… is this the best way to enable and disable tracing for debugging? These sorts of lines are scattered throughout the code, so I was hoping to not have to wrap blocks of if or whatever around them for housekeeping’s sake.
Will the compiler optimize these lines out of the assembly since they are provided a constant of false at build time?
Thanks for your insight!
I would use the ConditionalAttribute and a compiler flag to handle this instead.
This has the advantage of completely removing the methods from your production code – so the conditional check doesn’t even occur.
Doing this, you could make your own method, such as:
And then have a
TRACEflag in your debug/non-production build settings. This will cause the method to only exist in the compiled source (including the calls) when that flag is defined.