Table of Contents
System.Diagnostics.Contracts
Contract
Assert
Assume
ContractFailed
EndContractBlock
Ensures
EnsuresOnThrow
Exists
ForAll
Invariant
OldValue
Requires
Result
ValueAtReturn
ContractAbbreviatorAttribute
ContractAbbreviatorAttribute
ContractArgumentValidatorAttribute
ContractArgumentValidatorAttribute
ContractClassAttribute
ContractClassAttribute
TypeContainingContracts
ContractClassForAttribute
ContractClassForAttribute
TypeContractsAreFor
ContractFailedEventArgs
Condition
ContractFailedEventArgs
FailureKind
Handled
Message
OriginalException
SetHandled
SetUnwind
Unwind
ContractFailureKind
Assert
Assume
Invariant
Postcondition
PostconditionOnException
Precondition
ContractInvariantMethodAttribute
ContractInvariantMethodAttribute
ContractOptionAttribute
Category
ContractOptionAttribute
Enabled
Setting
Value
ContractPublicPropertyNameAttribute
ContractPublicPropertyNameAttribute
Name
ContractReferenceAssemblyAttribute
ContractReferenceAssemblyAttribute
ContractRuntimeIgnoredAttribute
ContractRuntimeIgnoredAttribute
ContractVerificationAttribute
ContractVerificationAttribute
Value
PureAttribute
PureAttribute
PureAttribute
System.Diagnostics.Contracts Namespace
The System.Diagnostics.Contracts namespace contains static classes for representing program contracts such as
preconditions, postconditions, and invariants.
Classes
Contract
ContractAbbreviatorAttribute
ContractArgumentValidatorAttribute
ContractClassAttribute
ContractClassForAttribute
ContractFailedEventArgs
ContractInvariantMethodAttribute
ContractOptionAttribute
ContractPublicPropertyNameAttribute
ContractReferenceAssemblyAttribute
ContractRuntimeIgnoredAttribute
ContractVerificationAttribute
Contains static methods for representing program contracts
such as preconditions, postconditions, and object invariants.
Defines abbreviations that you can use in place of the full
contract syntax.
Enables the factoring of legacy if-then-throw code into
separate methods for reuse, and provides full control over
thrown exceptions and arguments.
Specifies that a separate type contains the code contracts for
this type.
Specifies that a class is a contract for a type.
Provides methods and data for the ContractFailed event.
Marks a method as being the invariant method for a class.
Enables you to set contract and tool options at assembly,
type, or method granularity.
Specifies that a field can be used in method contracts when
the field has less visibility than the method.
Specifies that an assembly is a reference assembly that
contains contracts.
Identifies a member that has no run-time behavior.
Instructs analysis tools to assume the correctness of an
assembly, type, or member without performing static
verification.
PureAttribute
Indicates that a type or method is pure, that is, it does not
make any visible state changes.
Enums
ContractFailureKind
Specifies the type of contract that failed.
Contract Class
Contains static methods for representing program contracts such as preconditions, postconditions, and object
invariants.
D eclaration
public static class Contract
I nheritance H ierarchy
Object
Remarks
Code contract classes let you specify preconditions, postconditions, and object invariants in your code. Preconditions
are requirements that must be met when entering a method or property. Postconditions describe expectations at the
time the method or property code exits. Object invariants describe the expected state for a class that has no condition
problems. For more information about preconditions, postconditions, and object invariants, see Code Contracts.
For tools and detailed instructions for using code contracts, see Code Contracts on the MSDN DevLabs Web site.
Im p o rt a nt
You must use a binary rewriter to insert run-time enforcement of contracts. Otherwise, contracts such as the
System.Diagnostics.Contracts.Contract.Ensures method can only be tested statically and will not throw exceptions
during run time if a contract is violated. You can download the binary rewriter CCRewrite from Code Contracts on the
MSDN DevLabs Web site. CCRewrite comes with a Visual Studio add-in that enables you to activate run-time contract
enforcement from the project Properties page. The binary rewriter and the Visual Studio add-in do not ship with
Visual Studio 2010 or the Windows SDK.
Methods
Assert(Boolean)
Checks for a condition; if the condition is false , follows the escalation policy set for the analyzer.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition);
Parameters
condition Boolean
The conditional expression to test.
Assert(Boolean, String)
Checks for a condition; if the condition is false , follows the escalation policy set by the analyzer and displays the
specified message.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string userMessage);
Parameters
condition Boolean
The conditional expression to test.
userMessage String
A message to display if the condition is not met.
Assume(Boolean)
Instructs code analysis tools to assume that the specified condition is true , even if it cannot be statically proven to
always be true .
D eclaration
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Assume (bool condition);
Parameters
condition Boolean
The conditional expression to assume true .
Assume(Boolean, String)
Instructs code analysis tools to assume that a condition is true , even if it cannot be statically proven to always be
true , and displays a message if the assumption fails.
D eclaration
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Assume (bool condition, string userMessage);
Parameters
condition Boolean
The conditional expression to assume true .
userMessage String
The message to post if the assumption fails.
EndContractBlock()
Marks the end of the contract section when a method's contracts contain only preconditions in the if - then throw form.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EndContractBlock ();
Ensures(Boolean)
Specifies a postcondition contract for the enclosing method or property.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Ensures (bool condition);
Parameters
condition Boolean
The conditional expression to test. The expression may include OldValue<T>(T), ValueAtReturn<T>(T), and Result<T>() values.
Ensures(Boolean, String)
Specifies a postcondition contract for a provided exit condition and a message to display if the condition is false .
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Ensures (bool condition, string userMessage);
Parameters
condition Boolean
The conditional expression to test. The expression may include OldValue<T>(T) and Result<T>() values.
userMessage String
The message to display if the expression is not true .
EnsuresOnThrow<TException>(Boolean)
Specifies a postcondition contract for the enclosing method or property, based on the provided exception and
condition.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException> (bool condition) where TException : Exception;
Parameters
condition Boolean
The conditional expression to test.
EnsuresOnThrow<TException>(Boolean, String)
Specifies a postcondition contract and a message to display if the condition is false for the enclosing method or
property, based on the provided exception and condition.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException> (bool condition, string userMessage) where
TException : Exception;
Parameters
condition Boolean
The conditional expression to test.
userMessage String
The message to display if the expression is false .
Exists(Int32, Int32, Predicate<Int32>)
Determines whether a specified test is true for any integer within a range of integers.
D eclaration
public static bool Exists (int fromInclusive, int toExclusive, Predicate<int> predicate);
Parameters
fromInclusive Int32
The first integer to pass to predicate .
toExclusive Int32
One more than the last integer to pass to predicate .
predicate Predicate<Int32>
The function to evaluate for any value of the integer in the specified range.
Returns
Boolean
true if predicate returns true for any integer starting from fromInclusive to toExclusive - 1.
Exists<T>(IEnumerable<T>, Predicate<T>)
Determines whether an element within a collection of elements exists within a function.
D eclaration
public static bool Exists<T> (System.Collections.Generic.IEnumerable<T> collection, Predicate<T>
predicate);
Parameters
collection IEnumerable<T>
The collection from which elements of type T will be drawn to pass to predicate .
predicate Predicate<T>
The function to evaluate for an element in collection .
Returns
Boolean
true if and only if predicate returns true for any element of type T in collection .
ForAll(Int32, Int32, Predicate<Int32>)
Determines whether a particular condition is valid for all integers in a specified range.
D eclaration
public static bool ForAll (int fromInclusive, int toExclusive, Predicate<int> predicate);
Parameters
fromInclusive Int32
The first integer to pass to predicate .
toExclusive Int32
One more than the last integer to pass to predicate .
predicate Predicate<Int32>
The function to evaluate for the existence of the integers in the specified range.
Returns
Boolean
true if predicate returns true for all integers starting from fromInclusive to toExclusive - 1.
ForAll<T>(IEnumerable<T>, Predicate<T>)
Determines whether all the elements in a collection exist within a function.
D eclaration
public static bool ForAll<T> (System.Collections.Generic.IEnumerable<T> collection, Predicate<T>
predicate);
Parameters
collection IEnumerable<T>
The collection from which elements of type T will be drawn to pass to predicate .
predicate Predicate<T>
The function to evaluate for the existence of all the elements in collection .
Returns
Boolean
true if and only if predicate returns true for all elements of type T in collection .
Invariant(Boolean)
Specifies an invariant contract for the enclosing method or property.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Invariant (bool condition);
Parameters
condition Boolean
The conditional expression to test.
Invariant(Boolean, String)
Specifies an invariant contract for the enclosing method or property, and displays a message if the condition for
the contract fails.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Invariant (bool condition, string userMessage);
Parameters
condition Boolean
The conditional expression to test.
userMessage String
The message to display if the condition is false .
OldValue<T>(T)
Represents values as they were at the start of a method or property.
D eclaration
public static T OldValue<T> (T value);
Parameters
value T
The value to represent (field or parameter).
Returns
T
The value of the parameter or field at the start of a method or property.
Requires(Boolean)
Specifies a precondition contract for the enclosing method or property.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Requires (bool condition);
Parameters
condition Boolean
The conditional expression to test.
Requires(Boolean, String)
Specifies a precondition contract for the enclosing method or property, and displays a message if the condition for
the contract fails.
D eclaration
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Requires (bool condition, string userMessage);
Parameters
condition Boolean
The conditional expression to test.
userMessage String
The message to display if the condition is false .
Requires<TException>(Boolean)
Specifies a precondition contract for the enclosing method or property, and throws an exception if the condition
for the contract fails.
D eclaration
public static void Requires<TException> (bool condition) where TException : Exception;
Parameters
condition Boolean
The conditional expression to test.
Requires<TException>(Boolean, String)
Specifies a precondition contract for the enclosing method or property, and throws an exception with the provided
message if the condition for the contract fails.
D eclaration
public static void Requires<TException> (bool condition, string userMessage) where TException :
Exception;
Parameters
condition Boolean
The conditional expression to test.
userMessage String
The message to display if the condition is false .
Result<T>()
Represents the return value of a method or property.
D eclaration
public static T Result<T> ();
Returns
T
Return value of the enclosing method or property.
ValueAtReturn<T>(T)
Represents the final (output) value of an out parameter when returning from a method.
D eclaration
public static T ValueAtReturn<T> (out T value);
Parameters
value T
The out parameter.
Returns
T
The output value of the out parameter.
Events
ContractFailed
Occurs when a contract fails.
D eclaration
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public static event EventHandler<System.Diagnostics.Contracts.ContractFailedEventArgs>
ContractFailed;
Contract.Assert
I n this Article
Overloads
Assert(Boolean)
Checks for a condition; if the condition is false , follows the
escalation policy set for the analyzer.
Assert(Boolean, String)
Checks for a condition; if the condition is false , follows the
escalation policy set by the analyzer and displays the specified
message.
Assert(Boolean)
Checks for a condition; if the condition is false , follows the escalation policy set for the analyzer.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition);
Parameters
condition
Boolean
The conditional expression to test.
Attributes
ConditionalAttribute ConditionalAttribute
Remarks
The default escalation policy is to notify the attached debugger about a contract failure or to display an Assert dialog
box if a debugger is not attached. Optionally, the analyzer can be instructed to throw an exception.
Assert(Boolean, String)
Checks for a condition; if the condition is false , follows the escalation policy set by the analyzer and displays the
specified message.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
[System.Diagnostics.Conditional("DEBUG")]
public static void Assert (bool condition, string userMessage);
Parameters
condition
Boolean
The conditional expression to test.
userMessage
String
A message to display if the condition is not met.
Attributes
ConditionalAttribute ConditionalAttribute
Remarks
The default escalation policy is to notify the attached debugger about a contract failure or to display an Assert dialog
box if a debugger is not attached. Optionally, the analyzer can be instructed to throw an exception. The userMessage
parameter is passed to the debugger output. If userMessage is not a constant string literal, tools may not be able to
read it.
Contract.Assume
I n this Article
Overloads
Assume(Boolean)
Instructs code analysis tools to assume that the specified
condition is true , even if it cannot be statically proven to
always be true .
Assume(Boolean, String)
Instructs code analysis tools to assume that a condition is
true , even if it cannot be statically proven to always be
true , and displays a message if the assumption fails.
Assume(Boolean)
Instructs code analysis tools to assume that the specified condition is true , even if it cannot be statically proven to
always be true .
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Assume (bool condition);
Parameters
condition
Boolean
The conditional expression to assume true .
Attributes
ConditionalAttribute ConditionalAttribute
Remarks
At run time, using this method is equivalent to using the Assert(Boolean) method.
Assume(Boolean, String)
Instructs code analysis tools to assume that a condition is true , even if it cannot be statically proven to always be true
, and displays a message if the assumption fails.
[System.Diagnostics.Conditional("DEBUG")]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Assume (bool condition, string userMessage);
Parameters
condition
Boolean
The conditional expression to assume true .
userMessage
String
The message to post if the assumption fails.
Attributes
ConditionalAttribute ConditionalAttribute
Remarks
If userMessage is not a constant string literal, the contract may not be understood by tools.
At run time, using this method is equivalent to using the Assert(Boolean, String) method.
Contract.ContractFailed
I n this Article
Occurs when a contract fails.
[add: System.Security.SecurityCritical]
[remove: System.Security.SecurityCritical]
public static event EventHandler<System.Diagnostics.Contracts.ContractFailedEventArgs>
ContractFailed;
Returns
EventHandler<ContractFailedEventArgs>
Attributes
add: System.Security.SecurityCritical remove: System.Security.SecurityCritical
Remarks
The event information for this event is supplied by the System.Diagnostics.Contracts.ContractFailedEventArgs object
that is passed to the event handler. This event notifies a managed application environment such as an interactive
interpreter or a Web browser host that a contract has failed. Before doing so, it will raise an event that an application
can handle as it sees fit. For example, if code is being run in a testing framework, you can log a test failure and then end
the test.
The default implementation of the RaiseContractFailedEvent method in the .NET Framework class library is to call each
handler that is registered with the ContractFailed event. Exceptions thrown by handlers are ignored, but each handler
can indicate whether the failure is handled by calling the SetHandled method for the event arguments. If any handler
sets the failure as handled, the method returns null and no further action is taken. Alternatively, handlers can call the
SetUnwind method to instruct the code to unwind. In that case, an exception is thrown after all handlers have executed.
Contract.EndContractBlock
I n this Article
Marks the end of the contract section when a method's contracts contain only preconditions in the if - then - throw
form.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EndContractBlock ();
Attributes
ConditionalAttribute
Remarks
Most code already contains some parameter validation in the form of if - then - throw code. The contract tools
recognize if - then - throw statements as preconditions when the statements appear first inside a method, and the
entire set of such statements is followed by an explicit Contract method call, such as a Requires, Ensures,
EnsuresOnThrow, or EndContractBlock.
When if - then - throw statements appear in this form, the contract tools recognize them as legacy-require statements.
The EndContractBlock form is used only if no other contracts follow the if - then - throw sequences, but they should
still be tagged as legacy-requires.
Contract.Ensures
I n this Article
Overloads
Ensures(Boolean)
Specifies a postcondition contract for the enclosing method or
property.
Ensures(Boolean, String)
Specifies a postcondition contract for a provided exit condition
and a message to display if the condition is false .
Ensures(Boolean)
Specifies a postcondition contract for the enclosing method or property.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Ensures (bool condition);
Parameters
condition
Boolean
The conditional expression to test. The expression may include OldValue<T>(T), ValueAtReturn<T>(T), and Result<T>()
values.
Attributes
ConditionalAttribute
Examples
The following example shows how to use the Ensures method to ensure that an expected value is returned. This code
example is part of a larger example provided for the ContractClassAttribute class.
int IArray.Add(Object value)
{
// Returns the index in which an item was inserted.
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < ((IArray)this).Count);
return default(int);
}
Remarks
The condition parameter specifies a postcondition that is expected to be true when the enclosing method or
property returns normally.
This method call must be at the beginning of a method or property, before any other code.
You must use the binary rewriter (available at Code Contracts on the MSDN DevLabs Web site) for run-time
enforcement of this postcondition.
Ensures(Boolean, String)
Specifies a postcondition contract for a provided exit condition and a message to display if the condition is false .
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Ensures (bool condition, string userMessage);
Parameters
condition
Boolean
The conditional expression to test. The expression may include OldValue<T>(T) and Result<T>() values.
userMessage
String
The message to display if the expression is not true .
Attributes
ConditionalAttribute
Remarks
The condition parameter specifies a postcondition that is expected to be true when the enclosing method or
property returns normally.
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
You must use the binary rewriter (available at Code Contracts on the MSDN DevLabs Web site) for run-time
enforcement of this postcondition.
If userMessage is not a constant string literal, the contract may not be understood by tools.
Contract.EnsuresOnThrow
I n this Article
Overloads
EnsuresOnThrow<TException>(Boolean)
Specifies a postcondition contract for the enclosing method or
property, based on the provided exception and condition.
EnsuresOnThrow<TException>(Boolean, String)
Specifies a postcondition contract and a message to display if
the condition is false for the enclosing method or property,
based on the provided exception and condition.
EnsuresOnThrow<TException>(Boolean)
Specifies a postcondition contract for the enclosing method or property, based on the provided exception and
condition.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException> (bool condition) where TException : Exception;
Type Parameters
TException
The type of exception that invokes the postcondition check.
Parameters
condition
Boolean
The conditional expression to test.
Attributes
ConditionalAttribute
Remarks
The condition parameter specifies a postcondition that is expected to be true when the enclosing method or
property terminates abnormally and an exception of type TException is thrown.
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
You must use the binary rewriter for run-time enforcement of this postcondition.
EnsuresOnThrow<TException>(Boolean, String)
Specifies a postcondition contract and a message to display if the condition is false for the enclosing method or
property, based on the provided exception and condition.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void EnsuresOnThrow<TException> (bool condition, string userMessage) where TException
: Exception;
Type Parameters
TException
The type of exception that invokes the postcondition check.
Parameters
condition
Boolean
The conditional expression to test.
userMessage
String
The message to display if the expression is false .
Attributes
ConditionalAttribute
Remarks
The condition parameter specifies a postcondition that is expected to be true when the enclosing method or
property terminates abnormally and an exception of type TException is thrown. The message parameter specifies a
message to display if the condition is false .
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
You must use the binary rewriter for run-time enforcement of this postcondition.
If userMessage is not a constant string literal, the contract may not be understood by tools.
Contract.Exists
I n this Article
Overloads
Exists(Int32, Int32, Predicate<Int32>)
Determines whether a specified test is true for any integer
within a range of integers.
Exists<T>(IEnumerable<T>, Predicate<T>)
Determines whether an element within a collection of
elements exists within a function.
Exists(Int32, Int32, Predicate<Int32>)
Determines whether a specified test is true for any integer within a range of integers.
public static bool Exists (int fromInclusive, int toExclusive, Predicate<int> predicate);
Parameters
fromInclusive
Int32
The first integer to pass to predicate .
toExclusive
Int32
One more than the last integer to pass to predicate .
predicate
Predicate<Int32>
The function to evaluate for any value of the integer in the specified range.
Returns
Boolean
true
if predicate returns true for any integer starting from fromInclusive to toExclusive - 1.
Exceptions
ArgumentNullException
predicate
is null .
ArgumentException
toExclusive
is less than fromInclusive .
Remarks
The toExclusive parameter is one more than the last integer to facilitate using the length of a range of integers
starting at 0. For example, it would be set to 5 for integers 0 through 4.
Exists<T>(IEnumerable<T>, Predicate<T>)
Determines whether an element within a collection of elements exists within a function.
public static bool Exists<T> (System.Collections.Generic.IEnumerable<T> collection, Predicate<T>
predicate);
Type Parameters
T
The type that is contained in collection .
Parameters
collection
IEnumerable<T>
The collection from which elements of type T will be drawn to pass to predicate .
predicate
Predicate<T>
The function to evaluate for an element in collection .
Returns
Boolean
true
if and only if predicate returns true for any element of type T in collection .
Exceptions
ArgumentNullException
collection
or predicate is null .
Contract.ForAll
I n this Article
Overloads
ForAll(Int32, Int32, Predicate<Int32>)
Determines whether a particular condition is valid for all
integers in a specified range.
ForAll<T>(IEnumerable<T>, Predicate<T>)
Determines whether all the elements in a collection exist within
a function.
ForAll(Int32, Int32, Predicate<Int32>)
Determines whether a particular condition is valid for all integers in a specified range.
public static bool ForAll (int fromInclusive, int toExclusive, Predicate<int> predicate);
Parameters
fromInclusive
Int32
The first integer to pass to predicate .
toExclusive
Int32
One more than the last integer to pass to predicate .
predicate
Predicate<Int32>
The function to evaluate for the existence of the integers in the specified range.
Returns
Boolean
true
if predicate returns true for all integers starting from fromInclusive to toExclusive - 1.
Exceptions
ArgumentNullException
predicate
is null .
ArgumentException
toExclusive
is less than fromInclusive .
Examples
The following example demonstrates how to use the ForAll method to determine whether an array has a null element.
using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace AssumeEx
{
class Program
{
// Start application with at least two arguments
static void Main(string[] args)
{
args[1] = null;
Contract.Requires(args != null && Contract.ForAll(0, args.Length, i => args[i] !=
null));
// test the ForAll method. This is only for purpose of demonstrating how ForAll works.
CheckIndexes(args);
Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push(null);
numbers.Push("four");
numbers.Push("five");
Contract.Requires(numbers != null && !Contract.ForAll(numbers, (String x) => x !=
null));
// test the ForAll generic overload. This is only for purpose of demonstrating how
ForAll works.
CheckTypeArray(numbers);
}
private static bool CheckIndexes(string[] args)
{
try
{
if (args != null && !Contract.ForAll(0, args.Length,
throw new ArgumentException("The parameter array
return true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
return false;
}
}
private static bool CheckTypeArray(IEnumerable<String> xs)
{
try
{
if (xs != null && !Contract.ForAll(xs, (String x) =>
throw new ArgumentException("The parameter array
"indexes");
return true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
return false;
}
}
}
}
i => args[i] != null))
has a null element", "args");
x != null))
has a null element",
Remarks
The toExclusive parameter is one more than the last integer to facilitate using the length of a range of integers
starting at 0. For example, it would be set to 5 for integers 0 through 4.
ForAll<T>(IEnumerable<T>, Predicate<T>)
Determines whether all the elements in a collection exist within a function.
public static bool ForAll<T> (System.Collections.Generic.IEnumerable<T> collection, Predicate<T>
predicate);
Type Parameters
T
The type that is contained in collection .
Parameters
collection
IEnumerable<T>
The collection from which elements of type T will be drawn to pass to predicate .
predicate
Predicate<T>
The function to evaluate for the existence of all the elements in collection .
Returns
Boolean
true
if and only if predicate returns true for all elements of type T in collection .
Exceptions
ArgumentNullException
collection
or predicate is null .
Examples
The following example demonstrates how to use the ForAll method to determine whether a collection has a null
element.
using System;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace AssumeEx
{
class Program
{
// Start application with at least two arguments
static void Main(string[] args)
{
args[1] = null;
Contract.Requires(args != null && Contract.ForAll(0, args.Length, i => args[i] !=
null));
// test the ForAll method. This is only for purpose of demonstrating how ForAll works.
CheckIndexes(args);
Stack<string> numbers = new Stack<string>();
numbers.Push("one");
numbers.Push("two");
numbers.Push(null);
numbers.Push("four");
numbers.Push("five");
Contract.Requires(numbers != null && !Contract.ForAll(numbers, (String x) => x !=
null));
// test the ForAll generic overload. This is only for purpose of demonstrating how
ForAll works.
CheckTypeArray(numbers);
}
private static bool CheckIndexes(string[] args)
{
try
{
if (args != null && !Contract.ForAll(0, args.Length,
throw new ArgumentException("The parameter array
return true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
return false;
}
}
private static bool CheckTypeArray(IEnumerable<String> xs)
{
try
{
if (xs != null && !Contract.ForAll(xs, (String x) =>
throw new ArgumentException("The parameter array
"indexes");
return true;
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
return false;
}
}
}
}
i => args[i] != null))
has a null element", "args");
x != null))
has a null element",
Contract.Invariant
I n this Article
Overloads
Invariant(Boolean)
Specifies an invariant contract for the enclosing method or
property.
Invariant(Boolean, String)
Specifies an invariant contract for the enclosing method or
property, and displays a message if the condition for the
contract fails.
Invariant(Boolean)
Specifies an invariant contract for the enclosing method or property.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Invariant (bool condition);
Parameters
condition
Boolean
The conditional expression to test.
Attributes
ConditionalAttribute
Remarks
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. If the method is not
sealed, it should refer only to protected members, not private members, so that subclasses can be sure to maintain the
invariants.
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 based on the presence of 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.
Invariant(Boolean, String)
Specifies an invariant contract for the enclosing method or property, and displays a message if the condition for the
contract fails.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Invariant (bool condition, string userMessage);
Parameters
condition
Boolean
The conditional expression to test.
userMessage
String
The message to display if the condition is false .
Attributes
ConditionalAttribute
Remarks
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.
Contract.OldValue
I n this Article
Represents values as they were at the start of a method or property.
public static T OldValue<T> (T value);
Type Parameters
T
The type of value.
Parameters
value
The value to represent (field or parameter).
Returns
T
The value of the parameter or field at the start of a method or property.
Examples
The following example shows the use of the OldValue method to ensure that a count has been updated. This code
example is part of a larger example provided for the ContractClassAttribute class.
void IArray.Insert(int index, Object value)
{
Contract.Requires(index >= 0);
Contract.Requires(index <= ((IArray)this).Count); // For inserting immediately after the end.
Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) + 1);
}
Remarks
This method can be used only in the conditional expression for the Ensures contract.
T
Contract.Requires
I n this Article
Overloads
Requires(Boolean)
Specifies a precondition contract for the enclosing method or
property.
Requires(Boolean, String)
Specifies a precondition contract for the enclosing method or
property, and displays a message if the condition for the
contract fails.
Requires<TException>(Boolean)
Specifies a precondition contract for the enclosing method or
property, and throws an exception if the condition for the
contract fails.
Requires<TException>(Boolean, String)
Specifies a precondition contract for the enclosing method or
property, and throws an exception with the provided message
if the condition for the contract fails.
Requires(Boolean)
Specifies a precondition contract for the enclosing method or property.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Requires (bool condition);
Parameters
condition
Boolean
The conditional expression to test.
Attributes
ConditionalAttribute
Remarks
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
Use this method instead of the System.Diagnostics.Contracts.Contract.Requires<TException>(Boolean) method when
backward compatibility does not force you to throw a particular exception.
Requires(Boolean, String)
Specifies a precondition contract for the enclosing method or property, and displays a message if the condition for the
contract fails.
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public static void Requires (bool condition, string userMessage);
Parameters
condition
Boolean
The conditional expression to test.
userMessage
String
The message to display if the condition is false .
Attributes
ConditionalAttribute
Remarks
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
Use this method instead of the System.Diagnostics.Contracts.Contract.Requires<TException>(Boolean, String) method
when backward compatibility does not force you to throw a particular exception.
Requires<TException>(Boolean)
Specifies a precondition contract for the enclosing method or property, and throws an exception if the condition for the
contract fails.
public static void Requires<TException> (bool condition) where TException : Exception;
Type Parameters
TException
The exception to throw if the condition is false .
Parameters
condition
Boolean
The conditional expression to test.
Remarks
Im p o rt a nt
You must turn on run-time checking to use the Requires method. If run-time checking is turned off, the process will be
terminated. To obtain the tools for runtime checking, see Code Contracts on the MSDN DevLabs Web site.
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
Use this method instead of the System.Diagnostics.Contracts.Contract.Requires(Boolean) method when you want to
throw an exception if the precondition fails.
Requires<TException>(Boolean, String)
Specifies a precondition contract for the enclosing method or property, and throws an exception with the provided
Specifies a precondition contract for the enclosing method or property, and throws an exception with the provided
message if the condition for the contract fails.
public static void Requires<TException> (bool condition, string userMessage) where TException :
Exception;
Type Parameters
TException
The exception to throw if the condition is false .
Parameters
condition
Boolean
The conditional expression to test.
userMessage
String
The message to display if the condition is false .
Remarks
Im p o rt a nt
You must turn on run-time checking to use the Requires method. If run-time checking is turned off, the process will be
terminated. To obtain the tools for runtime checking, see Code Contracts on the MSDN DevLabs Web site.
This method call must be at the beginning of a method or property, before any other code.
This contract is exposed to clients; therefore, it must only reference members that are at least as visible as the enclosing
method.
Use this method instead of the System.Diagnostics.Contracts.Contract.Requires(Boolean, String) method when you
want to throw an exception if the precondition fails.
Contract.Result
I n this Article
Represents the return value of a method or property.
public static T Result<T> ();
Type Parameters
T
Type of return value of the enclosing method or property.
Returns
T
Return value of the enclosing method or property.
Examples
The following example shows how to use the <xref:System.Diagnostics.Contracts.Contract.Result``1*> method to
specify an expected return value. This code example is part of a larger example provided for the ContractClassAttribute
class.
int IArray.Add(Object value)
{
// Returns the index in which an item was inserted.
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < ((IArray)this).Count);
return default(int);
}
Remarks
This method can be used only in the conditional expression for the Ensures contract.
Contract.ValueAtReturn
I n this Article
Represents the final (output) value of an out parameter when returning from a method.
public static T ValueAtReturn<T> (out T value);
Type Parameters
T
The type of the out parameter.
Parameters
value
T
The out parameter.
Returns
T
The output value of the out parameter.
Remarks
This method can be used only in the conditional expression for the Ensures contract. As with the OldValue method, you
can omit the generic type parameter whenever the compiler is able to infer its type. The contract rewriter replaces the
method call with the value of the out parameter. The ValueAtReturn method may appear only in postconditions. The
argument to the method must be an out parameter or a field of a structure out parameter. The latter is also useful
when referring to fields in the postcondition of a structure constructor.
ContractAbbreviatorAttribute Class
Defines abbreviations that you can use in place of the full contract syntax.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractAbbreviatorAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Constructors
ContractAbbreviatorAttribute()
Initializes a new instance of the ContractAbbreviatorAttribute class.
D eclaration
public ContractAbbreviatorAttribute ();
ContractAbbreviatorAttribute
I n this Article
Initializes a new instance of the ContractAbbreviatorAttribute class.
public ContractAbbreviatorAttribute ();
ContractArgumentValidatorAttribute Class
Enables the factoring of legacy if-then-throw code into separate methods for reuse, and provides full control over
thrown exceptions and arguments.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractArgumentValidatorAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
If your code uses explicit if-then-throw code to validate parameters, you may be employing helper methods that
perform checks and throw particular exceptions on failure, as shown in the following example.
using System;
static class ValidationHelper
{
public static void NotNull(object argument, string parameterName)
{
if (argument == null) throw new ArgumentNullException(parameterName,
"The parameter cannot be null.");
}
}
public class Example
{
public void Execute(string value)
{
ValidationHelper.NotNull(value, "value");
// Body of method goes here.
}
}
In this example, Execute has an elective precondition specifying that the parameter value should not be null . To
enable the contract tools to recognize that the call to ValidationHelper.NotNull represents a contract, you can mark
the called method with the ContractArgumentValidatorAttribute attribute. The
System.Diagnostics.Contracts.Contract.EndContractBlock method call should be used to enable the tools to extract the
proper specifications for document generation and static checking, as follows.
using System;
using System.Diagnostics.Contracts;
static class ValidationHelper
{
[ContractArgumentValidator]
public static void NotNull(object argument, string parameterName)
{
if (argument == null) throw new ArgumentNullException(parameterName,
"The parameter cannot be null.");
Contract.EndContractBlock();
}
}
In addition to if-then-throw statements, the contract section of contract validator methods may contain calls to other
contract validator methods. However, no other contracts (such as System.Diagnostics.Contracts.Contract.Requires, or
System.Diagnostics.Contracts.Contract.Ensures) are allowed. Code that follows the
System.Diagnostics.Contracts.Contract.EndContractBlock call is ignored by all contract tools.
The following example shows a range argument validator written in terms of an existing NotNull validator method.
using System;
using System.Diagnostics.Contracts;
static class ValidationHelper
{
[ContractArgumentValidator]
public static void NotNull(object argument, string parameterName)
{
if (argument == null) throw new ArgumentNullException(parameterName,
"The parameter cannot be null.");
Contract.EndContractBlock();
}
[ContractArgumentValidator]
public static void InRange(object[] array, int index, string arrayName, string indexName)
{
NotNull(array, arrayName);
if (index < 0)
throw new ArgumentOutOfRangeException(indexName,
"The index cannot be negative.");
if (index >= array.Length)
throw new ArgumentOutOfRangeException(indexName,
"The index is outside the bounds of the array.");
Contract.EndContractBlock();
}
}
public class Example
{
public void Execute(object[] data, int position)
{
ValidationHelper.InRange(data, position, "data", "position");
// Body of method goes here.
}
}
From a specification point of view, the Execute method has the following three contracts:
Contract.Requires<ArgumentNullException>(data != null);
Contract.Requires<ArgumentOutOfRangeException>(position >= 0);
Contract.Requires<ArgumentOutOfRangeException>(position < data.Length);
In standard methods, calls to contract validator methods can be freely mixed with other contracts such as
System.Diagnostics.Contracts.Contract.Ensures or System.Diagnostics.Contracts.Contract.Requires.
Constructors
ContractArgumentValidatorAttribute()
Initializes a new instance of the ContractArgumentValidatorAttribute class.
D eclaration
public ContractArgumentValidatorAttribute ();
ContractArgumentValidatorAttribute
I n this Article
Initializes a new instance of the ContractArgumentValidatorAttribute class.
public ContractArgumentValidatorAttribute ();
ContractClassAttribute Class
Specifies that a separate type contains the code contracts for this type.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Interface |
System.AttributeTargets.Delegate, AllowMultiple=false, Inherited=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
[System.Diagnostics.Conditional("DEBUG")]
public sealed class ContractClassAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
Types that are marked with this attribute have code contracts that are included in a separate type. The type that
contains the contracts is specified in the constructor.
Constructors
ContractClassAttribute(Type)
Initializes a new instance of the ContractClassAttribute class.
D eclaration
public ContractClassAttribute (Type typeContainingContracts);
Parameters
typeContainingContracts Type
The type that contains the code contracts for this type.
Properties
TypeContainingContracts
Gets the type that contains the code contracts for this type.
D eclaration
public Type TypeContainingContracts { get; }
P roperty Value
Type
The type that contains the code contracts for this type.
ContractClassAttribute
I n this Article
Initializes a new instance of the ContractClassAttribute class.
public ContractClassAttribute (Type typeContainingContracts);
Parameters
typeContainingContracts
Type
The type that contains the code contracts for this type.
Examples
The following example shows how to use the ContractClassAttribute constructor to specify that the contracts for the
IArray interface are contained in the IArrayContracts class.
#define CONTRACTS_FULL
using System;
using System.Diagnostics.Contracts;
// An IArray is an ordered collection of objects.
[ContractClass(typeof(IArrayContract))]
public interface IArray
{
// The Item property provides methods to read and edit entries in the array.
Object this[int index]
{
get;
set;
}
int Count
{
get;
}
// Adds an item to the list.
// The return value is the position the new element was inserted in.
int Add(Object value);
// Removes all items from the list.
void Clear();
// Inserts value into the array at position index.
// index must be non-negative and less than or equal to the
// number of elements in the array. If index equals the number
// of items in the array, then value is appended to the end.
void Insert(int index, Object value);
// Removes the item at position index.
void RemoveAt(int index);
}
[ContractClassFor(typeof(IArray))]
internal abstract class IArrayContract : IArray
{
{
int IArray.Add(Object value)
{
// Returns the index in which an item was inserted.
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < ((IArray)this).Count);
return default(int);
}
Object IArray.this[int index]
{
get
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
return default(int);
}
set
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
}
}
public int Count
{
get
{
Contract.Requires(Count >= 0);
Contract.Requires(Count <= ((IArray)this).Count);
return default(int);
}
}
void IArray.Clear()
{
Contract.Ensures(((IArray)this).Count == 0);
}
void IArray.Insert(int index, Object value)
{
Contract.Requires(index >= 0);
Contract.Requires(index <= ((IArray)this).Count); // For inserting immediately after the
end.
Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) + 1);
}
void IArray.RemoveAt(int index)
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) - 1);
}
}
ContractClassAttribute.TypeContainingContracts
I n this Article
Gets the type that contains the code contracts for this type.
public Type TypeContainingContracts { get; }
Returns
Type
The type that contains the code contracts for this type.
ContractClassForAttribute Class
Specifies that a class is a contract for a type.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple=false, Inherited=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractClassForAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
Types that are marked with this attribute represent a code contract for another type. The type that the contract applies
to is specified in the constructor.
Constructors
ContractClassForAttribute(Type)
Initializes a new instance of the ContractClassForAttribute class, specifying the type the current class is a contract
for.
D eclaration
public ContractClassForAttribute (Type typeContractsAreFor);
Parameters
typeContractsAreFor Type
The type the current class is a contract for.
Properties
TypeContractsAreFor
Gets the type that this code contract applies to.
D eclaration
public Type TypeContractsAreFor { get; }
P roperty Value
Type
The type that this contract applies to.
ContractClassForAttribute
I n this Article
Initializes a new instance of the ContractClassForAttribute class, specifying the type the current class is a contract for.
public ContractClassForAttribute (Type typeContractsAreFor);
Parameters
typeContractsAreFor
Type
The type the current class is a contract for.
Remarks
The following example shows how to use the ContractClassAttribute constructor to specify that the contracts in the type
apply to the IArray interface. This code example is part of a larger example provided for the ContractClassAttribute
class.
[ContractClassFor(typeof(IArray))]
internal abstract class IArrayContract : IArray
{
int IArray.Add(Object value)
{
// Returns the index in which an item was inserted.
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < ((IArray)this).Count);
return default(int);
}
Object IArray.this[int index]
{
get
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
return default(int);
}
set
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
}
}
public int Count
{
get
{
Contract.Requires(Count >= 0);
Contract.Requires(Count <= ((IArray)this).Count);
return default(int);
}
}
void IArray.Clear()
{
Contract.Ensures(((IArray)this).Count == 0);
}
void IArray.Insert(int index, Object value)
{
Contract.Requires(index >= 0);
Contract.Requires(index <= ((IArray)this).Count); // For inserting immediately after the
end.
Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) + 1);
}
void IArray.RemoveAt(int index)
{
Contract.Requires(index >= 0);
Contract.Requires(index < ((IArray)this).Count);
Contract.Ensures(((IArray)this).Count == Contract.OldValue(((IArray)this).Count) - 1);
}
}
ContractClassForAttribute.TypeContractsAreFor
I n this Article
Gets the type that this code contract applies to.
public Type TypeContractsAreFor { get; }
Returns
Type
The type that this contract applies to.
ContractFailedEventArgs Class
Provides methods and data for the ContractFailed event.
D eclaration
public sealed class ContractFailedEventArgs : EventArgs
I nheritance H ierarchy
Object
EventArgs
Remarks
A ContractFailedEventArgs object is passed to the System.Diagnostics.Contracts.Contract.ContractFailed event when a
contract fails. The ContractFailed event enables a managed application environment such as an interactive interpreter, a
Web browser host, a test harness, or a logging infrastructure to be notified of contract failures. The event requires full
trust.
Constructors
ContractFailedEventArgs(ContractFailureKind, String, String, Exception)
Provides data for the ContractFailed event.
D eclaration
public ContractFailedEventArgs (System.Diagnostics.Contracts.ContractFailureKind failureKind,
string message, string condition, Exception originalException);
Parameters
failureKind ContractFailureKind
One of the enumeration values that specifies the contract that failed.
message String
The message for the event.
condition String
The condition for the event.
originalException Exception
The exception that caused the event.
Properties
Condition
Gets the condition for the failure of the contract.
D eclaration
public string Condition { get; }
P roperty Value
String
The condition for the failure.
FailureKind
Gets the type of contract that failed.
D eclaration
public System.Diagnostics.Contracts.ContractFailureKind FailureKind { get; }
P roperty Value
ContractFailureKind
One of the enumeration values that specifies the type of contract that failed.
Handled
Indicates whether the ContractFailed event has been handled.
D eclaration
public bool Handled { get; }
P roperty Value
Boolean
true if the event has been handled; otherwise, false .
Message
Gets the message that describes the ContractFailed event.
D eclaration
public string Message { get; }
P roperty Value
String
The message that describes the event.
OriginalException
Gets the original exception that caused the ContractFailed event.
D eclaration
public Exception OriginalException { get; }
P roperty Value
Exception
The exception that caused the event.
Unwind
Indicates whether the code contract escalation policy should be applied.
D eclaration
public bool Unwind { get; }
P roperty Value
Boolean
true to apply the escalation policy; otherwise, false . The default is false .
Methods
SetHandled()
Sets the Handled property to true .
D eclaration
[System.Security.SecurityCritical]
public void SetHandled ();
SetUnwind()
Sets the Unwind property to true .
D eclaration
[System.Security.SecurityCritical]
public void SetUnwind ();
ContractFailedEventArgs.Condition
I n this Article
Gets the condition for the failure of the contract.
public string Condition { get; }
Returns
String
The condition for the failure.
ContractFailedEventArgs
I n this Article
Provides data for the ContractFailed event.
public ContractFailedEventArgs (System.Diagnostics.Contracts.ContractFailureKind failureKind, string
message, string condition, Exception originalException);
Parameters
failureKind
ContractFailureKind
One of the enumeration values that specifies the contract that failed.
message
String
The message for the event.
condition
String
The condition for the event.
originalException
The exception that caused the event.
Exception
ContractFailedEventArgs.FailureKind
I n this Article
Gets the type of contract that failed.
public System.Diagnostics.Contracts.ContractFailureKind FailureKind { get; }
Returns
ContractFailureKind
One of the enumeration values that specifies the type of contract that failed.
ContractFailedEventArgs.Handled
I n this Article
Indicates whether the ContractFailed event has been handled.
public bool Handled { get; }
Returns
Boolean
true
if the event has been handled; otherwise, false .
Remarks
If the System.Diagnostics.Contracts.Contract.ContractFailed event has not been handled, the debugger is notified. If no
debugger is attached, an Assert dialog box is displayed.
ContractFailedEventArgs.Message
I n this Article
Gets the message that describes the ContractFailed event.
public string Message { get; }
Returns
String
The message that describes the event.
ContractFailedEventArgs.OriginalException
I n this Article
Gets the original exception that caused the ContractFailed event.
public Exception OriginalException { get; }
Returns
Exception
The exception that caused the event.
ContractFailedEventArgs.SetHandled
I n this Article
Sets the Handled property to true .
[System.Security.SecurityCritical]
public void SetHandled ();
Attributes
SecurityCriticalAttribute
Remarks
The SetHandled method provides a way for the runtime analysis checker to indicate that a contract exception has been
handled. See the System.Diagnostics.Contracts.ContractFailedEventArgs.Handled property for more information.
ContractFailedEventArgs.SetUnwind
I n this Article
Sets the Unwind property to true .
[System.Security.SecurityCritical]
public void SetUnwind ();
Attributes
SecurityCriticalAttribute
Remarks
The SetUnwind method provides a way to indicate that the escalation policy for the code contract should be applied.
See the System.Diagnostics.Contracts.ContractFailedEventArgs.Unwind property for more information.
ContractFailedEventArgs.Unwind
I n this Article
Indicates whether the code contract escalation policy should be applied.
public bool Unwind { get; }
Returns
Boolean
true
to apply the escalation policy; otherwise, false . The default is false .
Remarks
If the return value is true , the escalation policy is to notify the attached debugger about a contract failure or to display
an Assert dialog box if a debugger is not attached.
W arning
This value should be set to false for analysis tools that run on a server (for example, ASP.NET).
ContractFailureKind Enum
Specifies the type of contract that failed.
D eclaration
public enum ContractFailureKind
I nheritance H ierarchy
Object
ValueType
Enum
Remarks
The ContractFailureKind enumeration is used by the System.Diagnostics.Contracts.ContractFailedEventArgs class.
Fields
Assert
An Assert contract failed.
Assume
An Assume contract failed.
Invariant
An Invariant contract failed.
Postcondition
An Ensures contract failed.
PostconditionOnException
An EnsuresOnThrow contract failed.
Precondition
A Requires contract failed.
ContractFailureKind.Assert
I n this Article
An Assert contract failed.
Assert
Returns
ContractFailureKind
ContractFailureKind.Assume
I n this Article
An Assume contract failed.
Assume
Returns
ContractFailureKind
ContractFailureKind.Invariant
I n this Article
An Invariant contract failed.
Invariant
Returns
ContractFailureKind
ContractFailureKind.Postcondition
I n this Article
An Ensures contract failed.
Postcondition
Returns
ContractFailureKind
ContractFailureKind.PostconditionOnException
I n this Article
An EnsuresOnThrow contract failed.
PostconditionOnException
Returns
ContractFailureKind
ContractFailureKind.Precondition
I n this Article
A Requires contract failed.
Precondition
Returns
ContractFailureKind
ContractInvariantMethodAttribute Class
Marks a method as being the invariant method for a class.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=false, Inherited=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractInvariantMethodAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
The invariant method can have any name, but it must return void and take no parameters. A suggested name for the
method is ObjectInvariant . The body of the invariant method must consist solely of one or more calls to the
System.Diagnostics.Contracts.Contract.Invariant method. A type can have more than one contract invariant method,
which can be public or private.
Constructors
ContractInvariantMethodAttribute()
Initializes a new instance of the ContractInvariantMethodAttribute class.
D eclaration
public ContractInvariantMethodAttribute ();
ContractInvariantMethodAttribute
I n this Article
Initializes a new instance of the ContractInvariantMethodAttribute class.
public ContractInvariantMethodAttribute ();
ContractOptionAttribute Class
Enables you to set contract and tool options at assembly, type, or method granularity.
D eclaration
[System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractOptionAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
The following table shows the currently supported options.
CATEG O R Y
S E T TING
V ALU E/EFFECT
contract
inheritance
true to turn contract inheritance on;
false to turn it off. The default is
true .
runtime
checking
true to turn run-time checking on;
false to turn it off. The default is
true .
You can use this attribute as illustrated in the following examples.
To turn off run-time checking for the entire assembly:
[assembly:ContractOption("runtime", "checking", false)]
To turn run-time contract checking on for a specific type:
[ContractOption("runtime", "checking", true)]
class TypeWithRuntimeChecking {
...
To turn run-time checking off for a specific method:
// Turn off all contract inheritance from interface IList<T>
[ContractOption("contract", "inheritance", false)]
class MyConcurrentList<T> : IList<T> {
...
}
[ContractOption("runtime", "checking", false)]
public override MyMethod(int x) {
// no inherited contracts checked at runtime,
// no invariants checked at runtime.
...
}
[ContractOption("runtime", "checking", false)]
public void MethodWithoutRuntimeChecking(...) {
...
}
}
Constructors
ContractOptionAttribute(String, String, Boolean)
Initializes a new instance of the ContractOptionAttribute class by using the provided category, setting, and
enable/disable value.
D eclaration
public ContractOptionAttribute (string category, string setting, bool enabled);
Parameters
category String
The category for the option to be set.
setting String
The option setting.
enabled Boolean
true to enable the option; false to disable the option.
ContractOptionAttribute(String, String, String)
Initializes a new instance of the ContractOptionAttribute class by using the provided category, setting, and value.
D eclaration
public ContractOptionAttribute (string category, string setting, string value);
Parameters
category String
The category of the option to be set.
setting String
The option setting.
value String
The value for the setting.
Properties
Category
Gets the category of the option.
D eclaration
public string Category { get; }
P roperty Value
String
The category of the option.
Enabled
Determines if an option is enabled.
D eclaration
public bool Enabled { get; }
P roperty Value
Boolean
true if the option is enabled; otherwise, false .
Setting
Gets the setting for the option.
D eclaration
public string Setting { get; }
P roperty Value
String
The setting for the option.
Value
Gets the value for the option.
D eclaration
public string Value { get; }
P roperty Value
String
String
The value for the option.
ContractOptionAttribute.Category
I n this Article
Gets the category of the option.
public string Category { get; }
Returns
String
The category of the option.
ContractOptionAttribute
I n this Article
Overloads
ContractOptionAttribute(String, String, Boolean)
Initializes a new instance of the ContractOptionAttribute class
by using the provided category, setting, and enable/disable
value.
ContractOptionAttribute(String, String, String)
Initializes a new instance of the ContractOptionAttribute class
by using the provided category, setting, and value.
ContractOptionAttribute(String, String, Boolean)
Initializes a new instance of the ContractOptionAttribute class by using the provided category, setting, and
enable/disable value.
public ContractOptionAttribute (string category, string setting, bool enabled);
Parameters
category
String
The category for the option to be set.
setting
String
The option setting.
enabled
true
Boolean
to enable the option; false to disable the option.
ContractOptionAttribute(String, String, String)
Initializes a new instance of the ContractOptionAttribute class by using the provided category, setting, and value.
public ContractOptionAttribute (string category, string setting, string value);
Parameters
category
String
The category of the option to be set.
setting
String
The option setting.
value
The value for the setting.
Remarks
String
There are only two category/setting options, and they can be set by either of the constructor overloads. You can use
this overload with the same settings as the ContractOptionAttribute(String, String, Boolean) overload by specifying
"true" or "false" in string format; for example:
[ContractOption("contract", "inheritance", "false")]
class MyConcurrentList<T> : IList<T> {
...
}
ContractOptionAttribute.Enabled
I n this Article
Determines if an option is enabled.
public bool Enabled { get; }
Returns
Boolean
true
if the option is enabled; otherwise, false .
ContractOptionAttribute.Setting
I n this Article
Gets the setting for the option.
public string Setting { get; }
Returns
String
The setting for the option.
ContractOptionAttribute.Value
I n this Article
Gets the value for the option.
public string Value { get; }
Returns
String
The value for the option.
ContractPublicPropertyNameAttribute Class
Specifies that a field can be used in method contracts when the field has less visibility than the method.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Field)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractPublicPropertyNameAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
When you apply the ContractPublicPropertyNameAttribute attribute to a field, that field can be used in the code
contracts for a method when the field has less visibility than the method. There must be a visible property that is
equivalent to the value of the field. For example, you can use this attribute if the method is public, but the field is
private.
Constructors
ContractPublicPropertyNameAttribute(String)
Initializes a new instance of the ContractPublicPropertyNameAttribute class.
D eclaration
public ContractPublicPropertyNameAttribute (string name);
Parameters
name String
The property name to apply to the field.
Properties
Name
Gets the property name to be applied to the field.
D eclaration
public string Name { get; }
P roperty Value
String
The property name to be applied to the field.
ContractPublicPropertyNameAttribute
I n this Article
Initializes a new instance of the ContractPublicPropertyNameAttribute class.
public ContractPublicPropertyNameAttribute (string name);
Parameters
name
The property name to apply to the field.
String
ContractPublicPropertyNameAttribute.Name
I n this Article
Gets the property name to be applied to the field.
public string Name { get; }
Returns
String
The property name to be applied to the field.
ContractReferenceAssemblyAttribute Class
Specifies that an assembly is a reference assembly that contains contracts.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Assembly)]
public sealed class ContractReferenceAssemblyAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
A contract reference assembly is named assembly.Contracts.dll, where assembly is the name of the assembly from
which the contracts were extracted. A contract reference assembly contains the publicly visible interface of an assembly
and its contracts, but contains no code. Contract reference assemblies are used both by the runtime analyzer to inherit
contracts across assemblies, and during static verification to discover contracts on methods and types from assemblies
outside the assembly that is under analysis.
For more information about using attributes, see Attributes.
Constructors
ContractReferenceAssemblyAttribute()
Initializes a new instance of the ContractReferenceAssemblyAttribute class.
D eclaration
public ContractReferenceAssemblyAttribute ();
ContractReferenceAssemblyAttribute
I n this Article
Initializes a new instance of the ContractReferenceAssemblyAttribute class.
public ContractReferenceAssemblyAttribute ();
ContractRuntimeIgnoredAttribute Class
Identifies a member that has no run-time behavior.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Property,
AllowMultiple=false, Inherited=true)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractRuntimeIgnoredAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
Methods and properties that are marked with this attribute can be used within calls to
System.Diagnostics.Contracts.Contract methods, but they have no run-time behavior.
Constructors
ContractRuntimeIgnoredAttribute()
Initializes a new instance of the ContractRuntimeIgnoredAttribute class.
D eclaration
public ContractRuntimeIgnoredAttribute ();
ContractRuntimeIgnoredAttribute
I n this Article
Initializes a new instance of the ContractRuntimeIgnoredAttribute class.
public ContractRuntimeIgnoredAttribute ();
ContractVerificationAttribute Class
Instructs analysis tools to assume the correctness of an assembly, type, or member without performing static
verification.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Struct | System.AttributeTargets.Constructor |
System.AttributeTargets.Method | System.AttributeTargets.Property)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class ContractVerificationAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
Use ContractVerification(false) to explicitly mark an assembly, type, or member as not requiring verification. The
most specific element found (member, type, and then assembly) takes precedence. Applying this attribute to a property,
type, or assembly has the following effects:
When you apply it to a property, it applies to both the get accessor and the set accessor.
When you apply it to a type, it applies to all members of the type, including nested types.
When you apply it to an assembly, it applies to all types and members of the assembly.
Constructors
ContractVerificationAttribute(Boolean)
Initializes a new instance of the ContractVerificationAttribute class.
D eclaration
public ContractVerificationAttribute (bool value);
Parameters
value Boolean
true to require verification; otherwise, false .
Properties
Value
Gets the value that indicates whether to verify the contract of the target.
D eclaration
public bool Value { get; }
P roperty Value
Boolean
Boolean
true if verification is required; otherwise, false .
ContractVerificationAttribute
I n this Article
Initializes a new instance of the ContractVerificationAttribute class.
public ContractVerificationAttribute (bool value);
Parameters
value
true
Boolean
to require verification; otherwise, false .
ContractVerificationAttribute.Value
I n this Article
Gets the value that indicates whether to verify the contract of the target.
public bool Value { get; }
Returns
Boolean
true
if verification is required; otherwise, false .
PureAttribute Class
Indicates that a type or method is pure, that is, it does not make any visible state changes.
D eclaration
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Constructor |
System.AttributeTargets.Method | System.AttributeTargets.Property |
System.AttributeTargets.Event | System.AttributeTargets.Parameter |
System.AttributeTargets.Delegate, AllowMultiple=false, Inherited=true)]
[System.Diagnostics.Conditional("CONTRACTS_FULL")]
public sealed class PureAttribute : Attribute
I nheritance H ierarchy
Object
Attribute
Remarks
Methods and types that are marked with this attribute can be used in calls to System.Diagnostics.Contracts.Contract
methods. Pure methods do not make any visible state changes. This attribute is not enforced by the current analysis
tools; you should use this attribute only if you are sure that the methods are pure.
Constructors
PureAttribute()
Initializes a new instance of the PureAttribute class.
D eclaration
public PureAttribute ();
PureAttribute
I n this Article
Initializes a new instance of the PureAttribute class.
public PureAttribute ();
© Copyright 2026 Paperzz