Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Invariant Method (Boolean, String)
Collapse the table of content
Expand the table of content

Contract.Invariant Method (Boolean, String)

Specifies an invariant contract for the enclosing method or property, and displays a message if the condition for the contract fails.

Namespace:  System.Diagnostics.Contracts
Assemblies:   mscorlib (in mscorlib.dll)
  System.Diagnostics.Contracts (in System.Diagnostics.Contracts.dll)

[ConditionalAttribute("CONTRACTS_FULL")]
public static void Invariant(
	bool condition,
	string userMessage
)

Parameters

condition
Type: System.Boolean

The conditional expression to test.

userMessage
Type: System.String

The message to display if the condition is false.

Invariant contracts are contained within a method that is identified by the ContractInvariantMethodAttribute attribute; typically, the method is named ObjectInvariant.

  • This contract can be specified only in a dedicated invariant method that is declared on a class.

  • This contract is not exposed to clients; therefore, it may reference members that are less visible than the enclosing method.

  • You must use the binary rewriter for run-time enforcement of this invariant.

  • Invariants are conditionally defined on the CONTRACTS FULL symbol. During run-time checking, invariants are checked at the end of each public method. If an invariant mentions a public method in the same class, the invariant check that would normally happen at the end of that public method is disabled and checked only at the end of the outermost method call to that class. This also happens if the class is re-entered because of a call to a method on another class.

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Portable Class Library

Supported in: Portable Class Library
Show:
© 2015 Microsoft