Question

I have seen code which includes Contract.Assert like,

Contract.Assert(t != null);

Will using Contract.Assert have a negative impact on my production code?

Was it helpful?

Solution

According to the manual on page 11, they're only included in your assembly when the DEBUG symbol is defined (which, of course, includes Debug builds, but not Release builds (by default)).

OTHER TIPS

In addition to the runtime benefits of Contract.Assert, you can also consider the alternative of using Contract.Assume (Manual section 2.5 page 11) when making calls to legacy code which does not have contracts defined, and if you like having the static warning level cranked up on high (e.g. static checking level more warnings or all warnings - level 3+ - and Show Assumptions turned on).

Contract.Assume gives you the same run time benefits as Contract.Assert, but also suppresses static checks which can't be proven because of the legacy assembly.

e.g. in the below code, with static checking enabled and warnings set to level 3 gives the warning : CodeContracts: requires unproven: someString != null when checking the contracts of MethodDoesNotAllowNull

 var aString = Legacy.MethodWithNoContract();
 MethodDoesNotAllowNull(aString); 

  private void MethodDoesNotAllowNull(string someString)
  {
     Contract.Requires(someString != null);
  }

With Legacy Assembly code:

  public static string MethodWithNoContract()
  {
     return "I'm not really null :)";
  }

Assume suppresses the warning (but gives the run time Assert benefit in debug builds):

 var aString = LegacyAssembly.LegacyMethodWithNoContract();
 Contract.Assume(aString != null);
 MethodDoesNotAllowNull(aString);

This way, you still get the empirical runtime benefit of the Contract.Assert in debug builds.

As for good practices it is better to have a set of good unit tests. Then code contracts are not that necessary. They may be helpful, but are less important.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top