Information Technology Reference
In-Depth Information
Trace .WriteLine( "Exiting CheckState for Person" );
#endif
}
Using the #if and #endif pragmas, you've created an empty method in
your release builds. The CheckState() method gets called in all builds,
release and debug. It doesn't do anything in the release builds, but you pay
for the method call. You also pay a small cost to load and JIT the empty
routine.
This practice works fine but can lead to subtle bugs that appear only in
release builds. The following common mistake shows what can happen
when you use pragmas for conditional compilation:
public void Func()
{
string msg = null ;
#if DEBUG
msg = GetDiagnostics();
#endif
Console .WriteLine(msg);
}
Everything works fine in your debug build, but your release builds happily
print a blank message. That's not your intent. You goofed, but the compiler
couldn't help you. You have code that is fundamental to your logic inside
a conditional block. Sprinkling your source code with #if/#endif blocks
makes it hard to diagnose the differences in behavior with the different
builds.
C# has a better alternative: the Conditional attribute. Using the Condi-
tional attribute, you can isolate functions that should be part of your
classes only when a particular environment variable is defined or set to a
certain value. The most common use of this feature is to instrument your
code with debugging statements. The .NET Framework library already has
the basic functionality you need for this use. This example shows how to
use the debugging capabilities in the .NET Framework Library, to show
you how conditional attributes work and when to add them to your code.
When you build the Person object, you add a method to verify the object
invariants:
 
Search WWH ::




Custom Search