Code contracts – Where invariant method called?

I assume you already know code contracts and have heard about invariant methods. This post will demonstrate how simple code compiles with invariant method.
This simple class declares a method as invariant method:

public class InvariantExample
{
public void Method()
{
Console.WriteLine("In Method");
}

[
ContractInvariantMethod]
protected void InvariantMethod()
{
Contract.Invariant(2 > 1);
}
}

Using reflector we can see that Method compiles to:

public void Method()
{
Console.WriteLine("In Method");
this.$InvariantMethod$();
}

As we can see the compiled method ends with a call to our invariant method. Assuming we had more methods in our class we would have seen similar call in each one of them. The invariants is less explicit than most contracts features but it’s a powerful part of it, use wisely!

Advertisement