Thursday, May 26, 2016

Code Contracts in C#

Code contracts introduced in .NET Framework 4.0 is a useful but underutilized feature. It enables a developer to publish various conditions that are necessary within an application.

There is a  concept called Design by contract where you can  define pre-conditions, post-conditions, and invariants on class methods. The basic idea was for a method to define a contract which states conditions that must be true when the method gets called. This is also called as preconditions. The method must also define conditions that must be true when it finishes execution. This is called as postconditions. The method can also define conditions that should remain true while the program is running. This is called as invariants.


.NET 4.5 introduces a new feature in Code Contracts called as abbreviations. Abbreviations are useful in scenarios where some contracts are required repeatedly. So if a method contains multiple contracts, just decorate that method with the ContractAbbreviator attribute, and this enables it to be used within other methods requiring this contract.



Code Contracts in .NET 4.5 and 4.6

 Although you can use the classes in the namespace System.Diagnostics.Contracts available with .NET 4.0, there is no Code Contract ‘tooling’ available in Visual Studio 2013 or in the latest versions of the .NET Framework (.NET 4.5 onwards). You may see the Contract class in .NET 4.5 and above, but the class does not function until you manually install the Code Contract library. The Code Contract library has now been released as an open source framework available on GitHub https://github.com/Microsoft/CodeContracts.
You need to download and run the Code Contracts .msi file found athttps://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970 in order for Code Contracts to be available in Visual Studio 2013 and Visual Studio 2015. After the extensions are installed, a new tab appears in the properties of your solution called ‘Code Contracts’. You can specify the properties in this tab to configure Code Contracts in applications created using VS 2013 and VS 2015.

Ref. sites:
https://msdn.microsoft.com/en-us/library/dd264808(v=vs.100).aspx
http://www.dotnetcurry.com/csharp/1172/code-contracts-csharp-static-runtime-checks

No comments: