emma middlebrook wrote:
Jon
Thanks for your reply ...
If you don't have DEBUG defined, it won't get evaluated at all.
Yes, I got that far :-) I was really more interested in whether anyone
had a better way than the below usage of the DEBUG symbol i.e. using
the preprocessor *as well as* testing for the condition *as well as*
using Debug.Fail or Debug.Assert in that block too! Something just
doesn't seem right about this code - looks a bit clumsy. Or am I
worrying too much?
#ifdef DEBUG
string GetAssertMessag e()
{
... prepare a message string ...
}
#endif
void SomeMethod()
{
...
#ifdef DEBUG
if (!condition)
{
string message = GetAssertMessag e();
// could use Debug.Fail without condition
Debug.Assert(co ndition, GetAssertMessag e());
}
#endif
}
You could write your own Assert() wrapper method, decorate it with the
ConditionalAttr ibute so it only gets called when DEBUG is defined:
public class MyDebug {
[System.Diagnost ics.Conditional Attribute( "DEBUG")]
public static void Assert( bool condition) {
if (!condition) {
string msg = GetAssertMessag e();
System.Diagnost ics.Debug.Asser t(condition, msg);
}
}
}
Now, replace your Debug.Assert() calls with calls to MyDebug.Assert( ).
GetAssertMessag e() will only be evaluated when the assertion condition
fails, and the ConditionalAttr ibute tells the compiler to not bother
putting the IL for calls to the MyDebug.Assert( ) method in the assembly
unless DEBUG is defined.
Depending on the deployment requirements of your application, and
whether or not calls to MyDebug.Assert are made from different
assemblies than where MyDebug is implemented, you may want to place the
*body* (not the entire definition) of MyAssert() inside an "#if DEBUG"
block, because the ConditionalAttr ibute only affects the calls to the
method - the method itself still gets compiled to IL, regardless of the
build type.
You might want to decorate GetAssertMessag e() with the conditional
attribute as well, instead of placing it inside an "#if DEBUG" block.
Now that I mentioned that, I'll bet one reason you asked this question
is because you get compiler errors when calls to GetAssertMessag e() are
not inside an "#if DEBUG" block. Simply using the ConditionalAttr ibute
on it will fix that problem.
If your problem is really that actual runtime calls to
GetAssertMessag e() are too expensive in a DEBUG build, then you will
probably need to go with my first suggestion.
--
mikeb