I downloaded code contracts from here. After installing code contract, I tried to create my first project with code contracts. I created new console project name CodeContractTest . I added reference to Microsoft.Contracts library which is appeared in .Net references after installation.
I wrote following code this is clearly compiled without any warning.
However, after running this application we will encounter with IndexOutOfRangeException. This is occurred because illegal parameter in Swap method call.
Let take a look at new feature added to Visual Studio 2008. I open properties window of project. New tab is added named "Code Contracts". I checked "Perform Static Contract Checking" and "Implicit Array Bound Obligations". If I rebuild project new warnings and message will be appeared in Error window. ![](https://gkasoq.bay.livefilestore.com/y1pwEGUN0tRu6dxokdijnyldZr4WfWrx-nQi7pHU2mrIHyhTcbGo10ji8ayYdHYz-xNHOz73AGZuV8rXZPV428u5n_NWXjoc6Ht/SettingCodeContractOptions.png?psid=1)
Four warnings are about Array access and four suggestion message plus one summary message. ![](https://public.bay.livefilestore.com/y1pBs0IHM3468q69kDP_2J5RP29NNxZFXqQUBAVguOaynepL0KF5Jm2EKF2tqa8iZTOHcK9n5UKSWcFRux2i12O6w/ErrorAndWarnings.png?psid=1)
In order to improve code and get rid of warnings I should add preconditions in swap method. I added four line of precondition which assure item1 , item2 is in array boundary. I used Contract class and Requires static method which is used for preconditions it has two overloads first overload has a bool parameter. We can use this method to explicitly define the conditions of input parameters.
[sourcecode language="csharp"] static void Swap(string[] arr, int item1, int item2) { Contract.Requires(item1 < arr.Length); Contract.Requires(item1 >= 0); Contract.Requires(item2 < arr.Length); Contract.Requires(item2 >= 0); string temp; temp = arr[item1]; arr[item1] = arr[item2]; arr[item2] = temp; }[/sourcecode]
[sourcecode language="csharp"] Swap(new string[] { "Code", "Contract" }, 0, 1);[/sourcecode]
[sourcecode language="csharp"] static void Swap(string[] arr, int item1, int item2) { Contract.Requires(arr != null); Contract.Requires(item1 < arr.Length); Contract.Requires(item1 >= 0); Contract.Requires(item2 < arr.Length); Contract.Requires(item2 >= 0); string temp; temp = arr[item1]; arr[item1] = arr[item2]; arr[item2] = temp; }[/sourcecode] </div>In this case developer of Swap method define contract for input parameters and there is no need to swap caller know all swap code in order to prevent bad parameter calling.
You can download code from [here](https://gkasoq.bay.livefilestore.com/y1pw_b-tHzJKUgqKrlw9pLOxLozFqtBFlOmu3ovl6vcd255a9LLqPkMMBo6Zxe22f9NKvrEMAh0VZxgAKcFsGDsYA/CodeContractTest.zip?download&psid=1) ![kick it on DotNetKicks.com](https://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fahmadreza.com%2fgf%2fblog%2fcode-contracts-part-2-creating-my-first-project-with-code-contracts%2f)