// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Diagnostics.Contracts; public class Test { private int v = 0; [ContractInvariantMethod] protected void ObjectInvariant() { Contract.Invariant(v < 100); } public void M1() { Contract.Requires(1 <= v && v <= 10); Console.WriteLine(v); } public void M2() { Contract.Ensures(1 <= v && v <= 10); Console.WriteLine(v); } public void M3() { Contract.EnsuresOnThrow(1 <= v && v <= 10); throw new Exception("Ooops"); } public void M4() { v = 200; Console.WriteLine(v); } } public class Program { public static void Main(String[] args) { Test o = new Test(); o.M1(); // violates pre condition o.M2(); // violates post condition o.M3(); // violates post condition o.M4(); // violates invariant } }