9

I am just starting to learn about the code contracts library that comes standard with VS2010. One thing I am running into right away is what some of the contract clauses really mean.

For example, how are these two statements different?

Contract.Requires(!mycollection.Any(a => a.ID == newID));
Contract.Requires(!Contract.Exists(mycollection, a => a.ID == newID));

In other words, what does Contract.Exists do in practical purposes, either for a developer using my function, or for the static code analysis system?

2
  • @Chris Pebble, the possible duplicate talks about the difference between List.Exists to IEnumerable.Any. This one is related to Contract.Exists - it's a different context.
    – Elisha
    May 6, 2010 at 21:58
  • Good point. Pardon the mistake. May 6, 2010 at 22:07

2 Answers 2

4

The version that uses Contract.Exists is preferred due to its declarative nature. Another advantage is that the framework knows this contract and it has better chance of being "caught" in static analysis.

1
  • Can you elaborate what you mean by "preferred due to its declarative nature"? Also, does static analysis actually work with delegates? I would expect that the fact you can put arbitrary code into that lambda would nullify any possible static analysis.
    – scobi
    May 7, 2010 at 16:16
1

Ok, I found the answer. According to the Code Contracts User Manual, section 2.7.2:

"It is also possible to use the extension method System.Linq.Enumerable.Any instead of Contract.Exists ."

So they are equivalent. I will use Any instead of Exists, so it is consistent with the rest of our code.

Your Answer

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

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