195

I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?

2

9 Answers 9

241

In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

If you compile in Release, all Debug.Assert's are automatically left out.

9
  • 15
    how can I get the same behavior of Debug.Assert in Release mode? Commented Feb 10, 2011 at 15:24
  • 15
    Trace.Assert for release mode apparently refs: msdn.microsoft.com/en-us/library/… msdn.microsoft.com/en-us/library/e63efys0.aspx
    – Tim Abell
    Commented May 11, 2011 at 11:37
  • 8
    @HamishGrubijan And why would you want Debug.Assert in release mode? Commented Jan 5, 2012 at 7:26
  • 38
    IMO, omitting asserts from release code is like conducting lifeboat drills while docked and then leaving the lifeboats behind when you sail. :)
    – chrisd
    Commented Nov 13, 2012 at 13:46
  • 132
    Asserts are not a lifeboat, they're an iceberg detection system. Since the user isn't steering the ship, an assert in release code just tells them they're doomed; it doesn't let them avoid the iceberg.
    – Stefan
    Commented Apr 30, 2013 at 7:49
112

From Code Complete

8 Defensive Programming

8.2 Assertions

An assertion is code that’s used during development—usually a routine or macro—that allows a program to check itself as it runs. When a assertion is true, that means everything is operating as expected. When it’s false, that means it has detected an unexpected error in the code. For example, if the system assumes that a customer-information file will never have more than 50,000 records, the program might contain an assertion that the number of records is less than or equal to 50,000. As long as the number of records is less than or equal to 50,000, the assertion will be silent. If it encounters more than 50,000 records, however, it will loudly “assert” that there is a error in the program.

Assertions are especially useful in large, complicated programs and in high-reliability programs. They enable programmers to more quickly flush out mismatched interface assumptions, errors that creep in when the code is modified, and so on.

An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.

(…)

Normally, you don’t want users to see assertion messages in production code; assertions are primarily for use during development and maintenance. Assertions are normally compiled into the code at development time and compiled out of the code for production. During development, assertions flush out contradictory assumptions, unexpected conditions, bad values passed to routines, and so on. During production, they are compiled out of the code so that the assertions don’t degrade system performance.

2
  • 2
    The book, Writing Solid Code, also has a great discussion about the usage of assert. They are a great debugging tool!
    – Paul Kelly
    Commented Dec 15, 2016 at 21:51
  • 1
    Also, the customer-information file is not the best example of why and how to use assertions, as it's testing a condition that's outside the scope of the code. Files can be modified manually, or downloaded from somewhere long after the product ships.
    – Trap
    Commented Apr 24, 2022 at 20:24
43

You should use it for times when you don't want to have to breakpoint every little line of code to check variables, but you do want to get some sort of feedback if certain situations are present, for example:

Debug.Assert(someObject != null, "someObject is null! this could totally be a bug!");
2
  • 1
    If I add a line of code similar to yours above, running my program gives the following error: "error CS0103: The name 'Debug' does not exist in the current context". Do I need some kind of using statement to make it work? Commented Jun 2, 2018 at 11:22
  • 7
    @JoshDesmond System.Diagnostics
    – Sinjai
    Commented Jun 8, 2018 at 17:24
19

First of all Assert() method is available for Trace and Debug classes.
Debug.Assert() is executing only in Debug mode.
Trace.Assert() is executing in Debug and Release mode.

Here is an example:

        int i = 1 + 3;
        // Debug.Assert method in Debug mode fails, since i == 4
        Debug.Assert(i == 3);
        Debug.WriteLine(i == 3, "i is equal to 3");

        // Trace.Assert method in Release mode is not failing.
        Trace.Assert(i == 4);
        Trace.WriteLine(i == 4, "i is equla to 4");

        Console.WriteLine("Press a key to continue...");
        Console.ReadLine();

Run this code in Debug mode and then in Release mode.

enter image description here

You will notice that during Debug mode your code Debug.Assert statement fails, you get a message box showing the current stack trace of the application. This is not happening in Release mode since Trace.Assert() condition is true (i == 4).

WriteLine() method simply gives you an option of logging the information to Visual Studio output. enter image description here

1
  • It appears that the behavior has been changed since. If you debug the application using Visual Studio 2022 the debugger will break on the failed assertion and allow you to continue. When running the application under Debug configuration without the debugger attached, the program will fail with the output "Process terminated. Assertion failed."
    – bgh
    Commented Jun 7 at 6:37
17

Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!

5
  • 3
    Abort / Retry / Ignore is classic! Was it assertions that used to cause Windows 3.1 to display this all the time?
    – devlord
    Commented Oct 2, 2008 at 17:50
  • Basically it's because it uses a MessageBox, which as you say dates back to Windows 3.1, and only has predefined button labels. So you can understand why the hack came about, but not why it's still there in 2008!
    – Joe
    Commented Oct 2, 2008 at 19:16
  • 4
    @Joe This is something that should only be seen by developers not end users so updating it is probably an extremely low priority item. If it bothers you can modify the Debug.Listeners or Trace.Listeners collections to replace the default handler with one that does anything you want. Commented Oct 4, 2011 at 20:34
  • 7
    And well it's 2019 now and the same dialog box / buttons are still here!
    – Bouke
    Commented Mar 13, 2019 at 6:33
  • 1
    Nothing more permanent than a temporary measure Commented Jan 21 at 18:27
10

Assert allows you to assert a condition (post or pre) applies in your code. It's a way of documenting your intentions and having the debugger inform you with a dialog if your intention is not met.

Unlike a breakpoint, the Assert goes with your code and can be used to add additional detail about your intention.

10

Assert can help you give separate messaging behavior between testing and release. For example,

Debug.Assert(x > 2)

will only trigger a break if you are running a "debug" build, not a release build. There's a full example of this behavior here

5

Assertions feature heavily in Design by Contract (DbC) which as I understand was introducted/endorsed by Meyer, Bertand. 1997. Object-Oriented Software Contruction.

An important feature is that they mustn't produce side-effects, for example you can handle an exception or take a different course of action with an if statement(defensive programming).

Assertions are used to check the pre/post conditions of the contract, the client/supplier relationship - the client must ensure that the pre-conditions of the supplier are met eg. sends £5 and the supplier must ensure the post-conditions are met eg. delivers 12 roses. (Just simple explanation of client/supplier - can accept less and deliver more, but about Assertions). C# also introduces Trace.Assert(), which can be used for release code.

To answer the question yes they still useful, but can add complexity+readability to code and time+difficultly to maintain. Should we still use them? Yes, Will we all use them? Probably not, or not to the extent of how Meyer describes.

(Even the OU Java course that I learnt this technique on only showed simple examples and the rest of there code didn't enforce the DbC assertion rules on most of code, but was assumed to be used to assure program correctness!)

4

The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.

It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).

1
  • 7
    It is important to point out, though, that invalid parameters on public methods should throw argument exceptions. Only private methods should validate input with assertions. Values that come in from outside are always suspect! Commented Oct 2, 2008 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.