The Code contract comes from Microsoft's research project TEAM. The concept is "contractual design ". in the past, we wrote some methods and added instructions before each method to inform the caller of the parameters of these methods. however, there is a disadvantage in doing so, that the caller cannot comply with the call requirements. the Code contract mechanism provided by CLR4.0 ensures that the caller complies with these call rules. The Compiler checks the code during compilation and CLR checks during runtime. it is similar to the assertion mechanism of c ++. but it is richer than c ++.
All the code Contracts are defined in the System. Diagnostics. Contracts. CodeContract static class. Let's look at several common ones:
When the method body just enters, use:
CodeContract. Requires (x> = 0); you can understand it at first glance. It is affected by the compilation switch. For example, you can only use this code contract in debug mode.
CodeContract. RequiresAlways (x> = 0); basically the same as above, the only difference is that it is not affected by the compilation switch, that is, the Code contract must be included in both Debug and Release modes.
When the method body exits (these must be written at the beginning of the method body ):
CodeContract. Ensures (z! = Null); // when the method body is closed, it must be true if method closes successfully
CodeContract. EnsuresOnThrow <IOException> (z! = Null); // make sure the Grantuee some variable status of some variables in case of exceptions.
Object Invariant
Object constants ensure that certain conditions must be met when all public methods are returned. object constants are defined in a separate method. This method must be labeled using [ContractInvariantMethod. the method name does not matter, but the method must return void without parameters. The method body can have multiple CodeContract. invariant statement, such:
[ContractInvariantMethod]
Void ObjectInvariant (){
CodeContract. Invariant (someData> = 0 );
}