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...
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.