I was going through a question on SO which was about new features of c# 4.0 and jon skeet's answer had Code Contracts feature of C# 4.0.. But i really cant understand when to use them.. Any suggestion...
Asked
Active
Viewed 2,137 times
2 Answers
25
Whenever possible. For example, anywhere that you would use a guard clause at the beginning of a method like
public void Write(TextWriter tw, object o) {
if(tw == null) {
throw new ArgumentNullException("tw");
}
if(o == null) {
throw new ArgumentNullException("o");
}
tw.WriteLine(o.ToString());
}
you should instead use
public void Write(TextWriter tw, object o) {
Contract.Requires(tw != null);
Contract.Requires(o != null);
tw.WriteLine(o.ToString());
}
What is beautiful about Contract
is that they become public and can be made part of the documentation with no additional work on your part where as the guard clause were not public and could only be put into documentation with some heavy lifting. Therefore, with Contract
you can more clearly express requirements and promises in your code.

jason
- 236,483
- 35
- 423
- 525
-
3In addition to above where Contracts are used to check preconditions, similarly they can be used to validate post-conditions - for example, after part/full method body execution, asserting if some variable/object is in correct state. Besides, Contracts may also be evaluated statically (at compile time). – VinayC Dec 09 '10 at 04:35
-
@VinayC: Yes, that is what I was alluding too with "more clearly express [...] promises in your code." Thanks for elaborating for me. – jason Dec 09 '10 at 05:17
-
+1 to both of you; I couldn't have said it better. – koenmetsu Dec 09 '10 at 08:25
-
It's also worth mentioning that if you're writing new code, the recommendation of the CC team is that you shouldn't use `Requires
`, but just plain `Requires`. The ` – porges Dec 13 '10 at 03:56` version is designed just for replacing legacy `if ... throw` code which needs to remain exception-compatible.
5
what's really beautiful with contracts is that you don't have to hard wire those ugly argument name strings...
if(tw == null) throw new ArgumentNullException("tw");

Joseph Yaduvanshi
- 20,241
- 5
- 61
- 69
-
Well, you don't need CC to make this code nicer. You could easily write some helper method à la `Must.Be.NotNull(_ => someExpr);` It's a question of personal preference which is "nicer", so this is not the real advantage of using CC. – stakx - no longer contributing Jul 19 '12 at 19:23