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?
-
11By the way, if you're interested in asserts you should definitely delve into [code contracts](http://msdn.microsoft.com/en-us/library/dd264808.aspx). – MasterMastic Feb 19 '13 at 19:12
-
Possible duplicate of http://stackoverflow.com/questions/129120/when-should-i-use-debug-assert/ – Michael Freidgeim Apr 04 '13 at 10:35
9 Answers
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.

- 19,134
- 9
- 53
- 73

- 136,852
- 88
- 292
- 341
-
14how can I get the same behavior of Debug.Assert in Release mode? – Hamish Grubijan Feb 10 '11 at 15:24
-
15Trace.Assert for release mode apparently refs: http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.assert.aspx http://msdn.microsoft.com/en-us/library/e63efys0.aspx – Tim Abell May 11 '11 at 11:37
-
8@HamishGrubijan And why would you want `Debug.Assert` in release mode? – Camilo Martin Jan 05 '12 at 07:26
-
35IMO, omitting asserts from release code is like conducting lifeboat drills while docked and then leaving the lifeboats behind when you sail. :) – chrisd Nov 13 '12 at 13:46
-
128Asserts 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 Apr 30 '13 at 07:49
-
5But it would seem better to fail early at the point where you know the problem; less confusing. But in that case, I'm guessing it's better to throw an error or use code contracts. There's also Trace.Assert which applies in production code too, but do use the overload that includes a friendly message, and be aware that the user can ignore the error. – Jon Coombs Sep 23 '13 at 20:30
-
7Regarding when to use one or the other, see [this answer](http://stackoverflow.com/a/5031211/533837) - which I agree with. In short Asserts are mainly to test _your own assumptions_, made in _your own code_, including, but not limited to, private function calls to find the places where you have done something wrong _in your code_. Exceptions are for assumptions in methods that can be called by anybody, e.g. public methods called from code made by a third party, or when something _can go wrong_ regardless of assumption correctness (e.g. network error). – AnorZaken Sep 10 '15 at 12:32
-
4I like to think of an `Assert` as a comment on steroids. 1) It's a succinct way to communicate your assumptions to future programmers (including yourself); 2) it has no performance impact in Release; 3) It's much less likely to get stale than a traditional comment. – mwolfe02 Sep 24 '17 at 01:51
-
1Asserts in release are basically a more succinct way to check POST-CONDITIONS are valid. It follows the fail-fast convention to ensure exceptions are generated as close as possible to where an issue occurs which makes identifying the source of problem much easier. – AaronLS May 24 '21 at 10:49
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.

- 3,425
- 30
- 38
- 48

- 80,295
- 52
- 162
- 195
-
2The book, Writing Solid Code, also has a great discussion about the usage of assert. They are a great debugging tool! – zooropa Dec 15 '16 at 21:51
-
1Also, 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 Apr 24 '22 at 20:24
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!");

- 9,034
- 10
- 45
- 58
-
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? – Josh Desmond Jun 02 '18 at 11:22
-
7
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!

- 122,218
- 32
- 205
- 338
-
3Abort / Retry / Ignore is classic! Was it assertions that used to cause Windows 3.1 to display this all the time? – devlord Oct 02 '08 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 Oct 02 '08 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. – Dan Is Fiddling By Firelight Oct 04 '11 at 20:34
-
6And well it's 2019 now and the same dialog box / buttons are still here! – Bouke Mar 13 '19 at 06:33
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.
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.

- 3,377
- 3
- 20
- 28
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.

- 61,417
- 20
- 137
- 189
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!)

- 61
- 1
- 3
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).

- 2,849
- 20
- 31
-
7It 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! – Jeffrey L Whitledge Oct 02 '08 at 19:15