Skip to main content

Assert Contract

  • 2 minutes to read

Purpose

This Code Provider adds the Assert precondition to method parameter(s) or variable assignment. The precondition statically ensures the passed or assigned parameters are not empty.

You can use two different assertion types — Debug.Assert and Contract.Assert. If you need to check the precondition in a debug environment only, use the Debug.Assert Contract Code Provider, otherwise, use the Contract.Assert Contract Code Provider, and the precondition will be checked in both debug and release environments.

Availability

Available in the following cases.

  • When the caret is at the beginning of a method body. In this case, the contract will test all method parameters and strings.
  • When the caret is on a method’s parameter name. In this case, the contract will test only the selected parameter.
  • When the caret is on a variable assignment.

Note

This Code Provider may be unavailable for variables of a non-nullable type, for instance, Integer.

Usage

  1. Place the caret at the beginning of a method body.

    Note

    The blinking cursor shows the caret’s position at which the Code Provider is available.

    public void AddRecord(string name, object data) {
    //...
    }
    
  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.
  3. Select Add Contract | Contract.Assert Contract from the menu (Debug.Assert Contract if you need to check the precondition in debug environment only).

After execution, the Code Provider adds the assertion statement against all the method parameters.

public void AddRecord(string name, object data) {
    Contract.Assert(!string.IsNullOrEmpty(name), "name is null or empty.");
    Contract.Assert(data != null, "data is null.");

    //...
}

You can ask CodeRush to check arrays and collections length in code contracts. Refer to the Code Actions Settings topic for more information.

Note

If the source file does not contain reference to the System.Diagnostics or System.Diagnostics.Contracts namespace, CodeRush adds the corresponding reference.

See Also