473,394 Members | 1,866 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,394 software developers and data experts.

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(Person p)
{
if (p == null)
throw new ArgumentNullException("P");
....
}

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

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

Pete
Aug 1 '08 #1
10 3354
Debug.Assert is marked with [Conditional("DEBUG")], 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.ThrowIfNull("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 ArgumentNullException instead
of something like this which I presume gets skipped in Release build and
is also quicker to type?

public void DoSomething(Person 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...@gmail.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 ArgumentException 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 ArgumentNullException.
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(Person !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...@gmail.comwrote:
I know it has been discussed before, but a language tweak would be very
welcome here; something like:

public void DoSomething(Person !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
"correctness 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(Person 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("DEBUG")], 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.ThrowIfNull("person");
I wrote an evil little extension method a while ago:

[MethodImpl(MethodImplOptions.NoInlining)]
public static void CheckForNull(this object o)
{
if (o != null) return;
StackFrame frame = new StackFrame(1, true);
byte op =
frame.GetMethod().GetMethodBody().GetILAsByteArray ()[frame.GetILOffset()
- 6];
throw new
ArgumentNullException(frame.GetMethod().GetParamet ers().Length <=
(4 - (frame.GetMethod().IsStatic ? 0 : 1)) ?
frame.GetMethod().GetParameters()[op - (2 +
(frame.GetMethod().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
Jon Skeet [C# MVP] wrote:
On Aug 1, 2:00 pm, Marc Gravell <marc.grav...@gmail.comwrote:
>I know it has been discussed before, but a language tweak would be very
welcome here; something like:

public void DoSomething(Person !p) {...}

And let the compiler worry about it.

(although perhaps more meaningful syntax)

I'd go for "Person! person" to mirror "int? value".
This is exactly what Spec# uses. I *really* want that in C# 4 (or a C#3
version of Spec#)

Alun Harford
Aug 1 '08 #11

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.
4
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
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...
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: 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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
0
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...
0
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...

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.