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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s