473,748 Members | 2,470 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Debug.Assert puzzle!

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

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

void SomeMethod()
{
...
Debug.Assert(co ndition, GetAssertMessag e());
...
}

Even if condition is true, GetAssertMessag e() will still be evaluated
as it's a parameter to a function. How can I best avoid the cost of
GetAssertMessag e() 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 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
}

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 4529
emma middlebrook <em************ **@fastmail.fm> wrote:
I have a question regarding asserting ... here's some code:

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

void SomeMethod()
{
...
Debug.Assert(co ndition, GetAssertMessag e());
...
}

Even if condition is true, GetAssertMessag e() will still be evaluated
as it's a parameter to a function. How can I best avoid the cost of
GetAssertMessag e() 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.Diagnost ics;

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

static string GetMessage()
{
Console.WriteLi ne ("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.co m>
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 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
}

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, GetAssertMessag e());

?

GetAssertMessag e 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.co m>
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 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

Nov 15 '05 #5

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

Similar topics

6
25552
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
5879
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 software. Most language designers recognized this, see C/C++ and Java which supports an assert keyword. My question now is, will C# support in future a single keyword for System.Diagnostics.Debug.Assert(), just like lock is a keyword for...
1
1359
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 to not show it in release version ? #include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Diagnostics;
7
2914
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 using the following code in Page_Load event handler. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim intcount As Integer intcount = 0 For intcount = 0 To 4
9
2333
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 generate an assertion failure for unoptimized, debug builds. We did this to find and fix cases where we were relying upon finalization rather than pro-active Dispose() calls. For classes that introduced IDisposable() into the class hierarchy...
3
2095
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 come across anything, but is there anything in (VB).NET that would allow me to do this? TIA. -- Brian Cryer www.cryer.co.uk/brian
10
3390
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 am assuming this is the same with ..NET too? Debug.Assert isn't compiled into a Release build? The other thing I am curious about is this public void DoSomething(Person p) { if (p == null)
1
1685
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 returns a void and throws) is dangerous because your unit tests may pass but in actuality they fail. class TestClass { } TestClass a = new TestClass(); TestClass b = new TestClass(); Assert.ReferenceEquals(a, b);
2
9037
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 figure this problem out. Any suggestions? thanks Joel
1
9329
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9250
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8247
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4878
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.