'Design By Contract' in C#
c#, design-by-contract
Solution
C# 4.0 Code Contracts
Microsoft has released a library for design by contract in version 4.0 of the .net framework. One of the coolest features of that library is that it also comes with a static analysis tools (similar to FxCop I guess) that leverages the details of the contracts you place on the code.
Here are some Microsoft resources:
- The main Microsoft Research site
- The user manual
- The 2008 PDC presentation
- The 2009 PDC presentation
Here are some other resources:
- Code Contracts for .NET 4.0 - Spec# Comes Alive
- .NET Code Contracts and TDD Are Complementary
- Code Contracts Primer – Part 5: Utilizing Object Invariants
- Code Contracts Primer – Part 6 Interface Contracts
Problem
I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to: ``` public string Foo() { set { Assert.IsNotNull(value); Assert.IsTrue(value.Contains("bar")); _foo = value; } } ``` I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.