15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Code Contracts ❘ 463<br />

can also assign a global event h<strong>and</strong>ler to the event ContractFailed that is invoked for every failed contract<br />

during runtime. Invoking SetH<strong>and</strong>led() with the ContractFailedEventArgs parameter e stops the<br />

st<strong>and</strong>ard behavior of failures that would throw an exception.<br />

Contract.ContractFailed += (sender, e) =><br />

{<br />

Console.WriteLine(e.Message);<br />

e.SetH<strong>and</strong>led();<br />

};<br />

code snippet CodeContractsSamples/Program.cs<br />

Preconditions<br />

Preconditions check the parameters that are passed to a method. Requires() <strong>and</strong><br />

Requires() are preconditions that can be defined with the Contract class. With the<br />

Requires() method, a Boolean value must be passed, <strong>and</strong> an optional message string with the second<br />

parameter that is shown when the condition does not succeed. The following sample requires that the<br />

argument min be lower than or equal to the argument max.<br />

static void MinMax(int min, int max)<br />

{<br />

Contract.Requires(min i < 12));<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!