Code Contracts in CLR 4.0

Source: Internet
Author: User
Tags static class

The code contract comes from the Microsoft Research Project team, the idea is "contract design". In the past, we wrote some methods, preceded each method with descriptive text, telling the caller what the parameters of these methods are. However, there is a disadvantage that this does not allow the caller to comply with the calling requirement. The code contract mechanism provided by CLR4.0 can ensure that callers comply with these calling rules, compile-time with the compiler to check, runtime has the CLR to check. It is similar to the assertion mechanism of C + +. But richer than C + +.

All code contracts are defined in the System.Diagnostics.Contracts.CodeContract static class. Take a look at a few common:

When the method body just enters:

Codecontract.requires (x>= 0); A discerning eye understands that it is affected by a compiler switch, such as you can use this code contract only in debug mode.

Codecontract.requiresalways (x>= 0); Basically the same as the above, the only difference is that it is not affected by the compilation switch, that is, whether the debug or release mode should include the code contract.

When the method body exits (these must be written at the beginning of the method body):

// 方法体关闭时必须为真 must be true if method closes successfully 
CodeContract.Ensures(z != null);
// 确保发生异常时某些变量的状态 Grantuee some  variable status in 
CodeContract.EnsuresOnThrow(z !=  null);case of specific exceptions.

Object invariants

Object invariants ensure that certain conditions must be met when all public methods are returned. Object invariants are defined in a separate method, and this method has a [Contractinvariantmethod] callout. The method name does not matter, but the method must return void and there are no arguments, and the method body can have multiple codecontract.invariant statements, such as:

[ContractInvariantMethod]

  void ObjectInvariant() { 
CodeContract.Invariant(someData >= 0); 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.