473,732 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Debug.Assert

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(Per son p)
{
if (p == null)
throw new ArgumentNullExc eption("P");
....
}

Why do people tend to use exceptions such as ArgumentNullExc eption instead
of something like this which I presume gets skipped in Release build and is
also quicker to type?

public void DoSomething(Per son p)
{
Debug.Assert(p != null, "P is null");
....
}

Pete
Aug 1 '08 #1
10 3387
Debug.Assert is marked with [Conditional("DE BUG")], which means that
calls to it only get compiled if the caller has the DEBUG symbol defined.

So yes; calls to Debug.Assert will not be compiled into a release build,
as long as you don't define "DEBUG" ;-p

Re the null check; Well, I guess it depends on what the code is. If it
is a library you can't trust the caller, so you'd need to still check.
For UI work, you could argualy use an Assert, but you'd need to be sure
that you have 100% code coverage. But this check will be ridiculously
quick, so I'd probably leave it in in most cases.

Re typing, well, you could probably use a custom snippet if you
wanted... in C# 3 you could also use an extension method (confusing
fact: you can call extension methods on null instances) - so you might have:

person.ThrowIfN ull("person");

(note I renamed the variable to be meaningful; I'd recommend this...
it'll save pain in the long run).

Marc
Aug 1 '08 #2
Why do people tend to use exceptions such as ArgumentNullExc eption instead
of something like this which I presume gets skipped in Release build and
is also quicker to type?

public void DoSomething(Per son p)
{
Debug.Assert(p != null, "P is null");
....
}
It really boils down to whether it's something that can happen in your
release build or not. If you're serving up a release library to a 3rd party
in particular then you never know what someone might pass. OTOH, if it's
only being consumed by your own code, then an "Assert()" is usually fine
IMO. Some would still argue that an exception should be used however if only
to catch your own mistakes (those that make it into the release build by
accident). In my long experience however, I don't recall ever encountering
this situation. I therefore rely on "Assert()" extensively for all my own
code. Maybe it's not quite as safe, but relying on exceptions to catch
programmer errors in a release build just rubs me the wrong way. GIGO should
be understood by developers who need to apply diligence when they program.
An "Assert()" is normally sufficient for this IMO (even for 3rd party
developers for that matter) but it's really a personal choice.
Aug 1 '08 #3
Those were the rules I have imposed on myself in the past, so I am pleased
to see a couple of replies confirming that I am doing the right thing :-)
(note I renamed the variable to be meaningful; I'd recommend this... it'll
save pain in the long run).
I am more idle when writing in newsgroups ;-)
Thanks

Pete

Aug 1 '08 #4
On Aug 1, 3:26*pm, Marc Gravell <marc.grav...@g mail.comwrote:
Re the null check; Well, I guess it depends on what the code is. If it
is a library you can't trust the caller, so you'd need to still check.
For UI work, you could argualy use an Assert, but you'd need to be sure
that you have 100% code coverage. But this check will be ridiculously
quick, so I'd probably leave it in in most cases.
Technically, there's also a third option - Trace.Assert, which is in
release builds by default.

Even so, using ArgumentExcepti on is the standard .NET pattern, and I
don't see any good reason for avoiding it (saving 3 lines of code is
not a good reason). Also, VS Code Analysis has an option to enforce
validation of arguments, and the only way it supports is explicit
check and throw ArgumentNullExc eption.
Aug 1 '08 #5
I know it has been discussed before, but a language tweak would be very
welcome here; something like:

public void DoSomething(Per son !p) {...}

And let the compiler worry about it.

(although perhaps more meaningful syntax)
Aug 1 '08 #6
On Aug 1, 2:00*pm, Marc Gravell <marc.grav...@g mail.comwrote:
I know it has been discussed before, but a language tweak would be very
welcome here; something like:

public void DoSomething(Per son !p) {...}

And let the compiler worry about it.

(although perhaps more meaningful syntax)
I'd go for "Person! person" to mirror "int? value".
Mads and I discussed this a bit back in 2005. It's the obvious "4th
box" to fill in for the value/reference, nullable/non-nullable matrix.

I'd be happy if it were just a shortcut for automatically creating
null-checking code at the start of methods, even without the
"correctnes s proving" which would also be possible.

Jon
Aug 1 '08 #7
Yes, that makes a lot more sense.

Marc\
Aug 1 '08 #8
I've seen (somewhere) an example of using something like PostSharp to
enforce it

[NotNull<Person> ("person")]
public void DoSomething(Per son person)
{
}

But at best it makes me mmm and ahhh a bit, doesn't jump out at me as a
great solution.

Aug 1 '08 #9
Marc Gravell wrote:
Debug.Assert is marked with [Conditional("DE BUG")], which means that
calls to it only get compiled if the caller has the DEBUG symbol defined.

So yes; calls to Debug.Assert will not be compiled into a release build,
as long as you don't define "DEBUG" ;-p

Re the null check; Well, I guess it depends on what the code is. If it
is a library you can't trust the caller, so you'd need to still check.
For UI work, you could argualy use an Assert, but you'd need to be sure
that you have 100% code coverage. But this check will be ridiculously
quick, so I'd probably leave it in in most cases.

Re typing, well, you could probably use a custom snippet if you
wanted... in C# 3 you could also use an extension method (confusing
fact: you can call extension methods on null instances) - so you might
have:

person.ThrowIfN ull("person");
I wrote an evil little extension method a while ago:

[MethodImpl(Meth odImplOptions.N oInlining)]
public static void CheckForNull(th is object o)
{
if (o != null) return;
StackFrame frame = new StackFrame(1, true);
byte op =
frame.GetMethod ().GetMethodBod y().GetILAsByte Array()[frame.GetILOffs et()
- 6];
throw new
ArgumentNullExc eption(frame.Ge tMethod().GetPa rameters().Leng th <=
(4 - (frame.GetMetho d().IsStatic ? 0 : 1)) ?
frame.GetMethod ().GetParameter s()[op - (2 +
(frame.GetMetho d().IsStatic ? 0 : 1))].Name :
"An argument was null, but I'm not sure which one.");
}

No need to pass the parameter name.

Alun Harford
Aug 1 '08 #10

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

Similar topics

6
25550
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.
4
4529
by: emma middlebrook | last post by:
I have a question regarding asserting ... here's some code: string GetAssertMessage() { ... prepare a message string and return it... } void SomeMethod() { ...
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
1358
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
2913
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
2094
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
1
1684
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
0
9447
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
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
9181
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
8186
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...
0
6031
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();...
1
3261
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
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
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.