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.
Spec# is a popular microsoft research project that allows for some DBC constructs, like checking post and pre conditions. For example a binary search can be implemented with pre and post conditions along with loop invariants. This example and more:
Note that using the Spec# language yields compile time checking for DBC constructs, which to me, is the best way to take advantage of DBC. Often, relying on runtime assertions becomes a headache in production and people generally elect to use exceptions instead.
There are other languages that embrace DBC concepts as first class constructs, namely Eiffel which is also available for the .NET platform.
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:
Here are some other resources:
There has an answer in .net Fx 4.0:
System.Diagnostics.Contracts
http://msdn.microsoft.com/en-us/library/dd264808.aspx
http://www.codeproject.com/KB/cs/designbycontract.aspx
The most straightforward way, and the way used in the .NET Framework itself, is to do: