473,387 Members | 1,669 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Debug.Assert puzzle!

I have a question regarding asserting ... here's some code:

string GetAssertMessage()
{
... prepare a message string and return it...
}

void SomeMethod()
{
...
Debug.Assert(condition, GetAssertMessage());
...
}

Even if condition is true, GetAssertMessage() will still be evaluated
as it's a parameter to a function. How can I best avoid the cost of
GetAssertMessage() if the condition is false and not in DEBUG mode? I
also read that I shouldn't really put function calls into an Assert
statement (MSDN "Assertions in Managed Code").

Idea 1:

#ifdef DEBUG

string GetAssertMessage()
{
... prepare a message string ...
}

#endif

void SomeMethod()
{
...
#ifdef DEBUG
if (!condition)
{
string message = GetAssertMessage();

// could use Debug.Fail without condition
Debug.Assert(condition, GetAssertMessage());
}
#endif
}

Surely there must be something a little more elegant than this? It
just makes the code ugly.

Any ideas or have I done the best I can here?

Thanks!

Emma Middlebrook
em*************@fastmail.fm
Nov 15 '05 #1
4 4499
emma middlebrook <em**************@fastmail.fm> wrote:
I have a question regarding asserting ... here's some code:

string GetAssertMessage()
{
... prepare a message string and return it...
}

void SomeMethod()
{
...
Debug.Assert(condition, GetAssertMessage());
...
}

Even if condition is true, GetAssertMessage() will still be evaluated
as it's a parameter to a function. How can I best avoid the cost of
GetAssertMessage() if the condition is false and not in DEBUG mode? I
also read that I shouldn't really put function calls into an Assert
statement (MSDN "Assertions in Managed Code").


If you don't have DEBUG defined, it won't get evaluated at all. Here's
some sample code:

using System;
using System.Diagnostics;

public class Test
{
static void Main(string[] args)
{
Debug.Assert (true, GetMessage());
}

static string GetMessage()
{
Console.WriteLine ("GetMessage called");
return "message";
}
}

When DEBUG is defined, "GetMessage called" will be produced on the
console. When it's not, the message won't appear.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
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 GetAssertMessage()
{
... prepare a message string ...
}
#endif

void SomeMethod()
{
...
#ifdef DEBUG
if (!condition)
{
string message = GetAssertMessage();

// could use Debug.Fail without condition
Debug.Assert(condition, GetAssertMessage());
}
#endif
}

Thanks!

Emma Middlebrook
em**************@fastmail.fm
Nov 15 '05 #3
emma middlebrook <em**************@fastmail.fm> wrote:
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?


I think you're worrying too much - what's wrong with just:

Debug.Assert (condition, GetAssertMessage());

?

GetAssertMessage doesn't get invoked when DEBUG isn't defined, so
what's the disadvantage? You end up with a *slightly* larger assembly
(as the method is still present) but it'll never even be JITted.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
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 GetAssertMessage()
{
... prepare a message string ...
}
#endif

void SomeMethod()
{
...
#ifdef DEBUG
if (!condition)
{
string message = GetAssertMessage();

// could use Debug.Fail without condition
Debug.Assert(condition, GetAssertMessage());
}
#endif
}

You could write your own Assert() wrapper method, decorate it with the
ConditionalAttribute so it only gets called when DEBUG is defined:

public class MyDebug {
[System.Diagnostics.ConditionalAttribute( "DEBUG")]
public static void Assert( bool condition) {
if (!condition) {
string msg = GetAssertMessage();
System.Diagnostics.Debug.Assert(condition, msg);
}
}
}
Now, replace your Debug.Assert() calls with calls to MyDebug.Assert().
GetAssertMessage() will only be evaluated when the assertion condition
fails, and the ConditionalAttribute 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 ConditionalAttribute 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 GetAssertMessage() 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 GetAssertMessage() are
not inside an "#if DEBUG" block. Simply using the ConditionalAttribute
on it will fix that problem.

If your problem is really that actual runtime calls to
GetAssertMessage() are too expensive in a DEBUG build, then you will
probably need to go with my first suggestion.

--
mikeb

Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Alexander Malkis | last post by:
Why do programmers like to use NDEBUG instead of DEBUG? -- Best regards, Alex. PS. To email me, remove "loeschedies" from the email address given.
2
by: cody | last post by:
System.Diagnostics.Debug.Assert(); Hello??? A language should encourage programmers to heavily use the assert-feature, since it improves safety, stability, readability and maintainability of...
1
by: High and dRy | last post by:
Hello, I created a simple .NET C++ console application. And the Debug::Assert(false) statement is popping a message box in release version also. Any idea why ? Any complier settings I need to do...
7
by: Srinivasa Rao | last post by:
I have read in one article that when we compile the application in release mode, all the debug classes and properties will be automatically removed from the code. I tried to implement this thing by...
9
by: Bern McCarty | last post by:
I am porting stuff from MEC++ syntax to the new C++/CLI syntax. Something that we did in the old syntax that proved to be very valuable was to make sure that the finalizer would purposefully...
3
by: Brian Cryer | last post by:
It would be very handy to be able to stop the debugger on parts of code without having to explicitly set a breakpoint - either a "debugger.break" or "debug.assert" type of thing would do. I've not...
10
by: Peter Morris | last post by:
In Delphi I used to use Assert as a development aid. During debug it would ensure that certain conditions were met but in the Release build the Asserts were not compiled into the application. I...
1
by: =?Utf-8?B?am1hZ2FyYW0=?= | last post by:
Why does the call to Debug.AssertReferenceEquals not raise a UnitTesting exception but the call to Assert.IsTrue does? This inconsistency (Assert.ReferenceEquals returns a bool and Assert.IsTrue...
2
by: joelkeepup | last post by:
Hi, I made a change this morning and now im getting an error that says either "a is undefined or null" or "e is undefined or null" the microsoft ajax line is below, I have no idea how to...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.