Debug.Assert vs Code Contract usage

Carbine picture Carbine · Dec 16, 2013 · Viewed 9.8k times · Source

When should I debug.assert over code contracts or vice versa? I want to check precondition for a method and I am confused to choose one over the other. I have unit tests where I want to test failure scenarios and expect exceptions.

Is it a good practice to use Debug.Assert and Code contract on the same method. If so what would be the order in which the code should be written?

Debug.Assert(parameter!= null);
Contract.Requires<ArgumentNullException>(parameter != null, "parameter");

or

Contract.Requires<ArgumentNullException>(parameter != null, "parameter");
Debug.Assert(parameter!= null);

Is there any rationale behind it?

Answer

Dweeberly picture Dweeberly · Dec 16, 2013

These are different things. A debug assert is only executed when the code is compiled as debug and therefore will only check/assert under debug. The idea is to use this for "sanity checks" for code you are developing. Code contracts can be used in either debug or release. They assure that pre and post conditions of methods comply with the expectations of the method (meet the contract). There is also a testing framework that provides similar functionality, designed for checking test compliance.

Use Debug.Assert when you want ensure that certain things are as you expect when developing the code (and in later maintenance development).

Use code contracts when you want to assure that conditions are true in both debug and release. Contracts also allow certain forms of static analysis that can be helpful in verifying that your program is "correct".

Use the Testing framework assertions when creating unit tests.