Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make .NET assertion throw an exception in release build

Tags:

.net

assert

We have a bunch of .NET assertions throughout our code, which we never see fail. If for some reason an assertion did fail, we would rather terminate the process and generate a crash dump than corrupt our users' data.

We have all the architecture set up to create a memory dump upon an unhandled exception, so we would like our Assertions to behave that way in a release build. Is there a way of doing this neatly, or do we just need to replace all our Assert calls with some other function that asserts and then throws?

like image 472
Smashery Avatar asked Mar 16 '26 01:03

Smashery


2 Answers

One option is to use Trace.Assert instead of Debug.Assert.

From the Remarks section of the MSDN page:

Use the Trace.Assert method if you want to do assertions in release builds. The Debug.Assert method works only in debug builds.

EDIT: In response to the comment:

The reason for the existence of Trace.Assert is to give the same functionality as Debug.Assert but in production builds. You should be able to use the same infrastructure that you use for crash dumps on Debug.Assert, but you'll have to reference Trace instead of Debug. From the MSDN article Assertions in Managed Code:

For example, you could override the TraceListener.Fail method to write to an event log instead of displaying the Assertion Failed dialog box.

In your case, you could probably reuse the same TraceListener that you are (probably - I don't know unless you say so) using today to generate a crash dump. The only difference is that you'd add it to Trace.Listeners instead of Debug.Listeners.

like image 55
Adam Mihalcin Avatar answered Mar 17 '26 15:03

Adam Mihalcin


You have three options in my opinion:

  • Deploy the debug build, instead of release build, to your clients. If you're looking to get an accurate stack trace this is also a better option. This is what debug build is meant for.

  • Another option is Code Contracts. This throws a RaiseContractFailedEvent by default if the contract is not met.

  • Use a Guard utility instead of out of the box Assert function.

like image 45
Hadi Eskandari Avatar answered Mar 17 '26 14:03

Hadi Eskandari