Project Description

LightContracts is a simple, small and lightweight library supporting 'Design by Contract' style of programming. It let you specify simple pre- and postconditions with a fluent API, without using an heavy AOP framework. It is developed in C#.


In his famous book "Object-Oriented Software Construction" Bertrand Meyer described a design technique called "Design by Contract" (DBC) which can improve software quality dramatically. His programming language Eiffel supports this design technique inherently. This valuable technique is universal and widely accepted and can be used regardless in which programming language you are developing. To apply this technique also in .NET several initiatives have been started ( E.g. ContractDriven.NET or ContractN). Recently Microsoft announced that its Code Contracts projects would be included as part of .Net 4.0.

Why should I use LightContracts

All mentioned projects are quite heavyweight. They are using aspect-oriented programming (AOP) frameworks to inject code, require to inherit from a base class or need special tools and compiler settings. My observation is that 90% of all assertions are very simple and do not justify the use of heavy tools. LightContracts is a small DLL which can simply be referenced by any .NET project, without installing additional software. It has a fluent API which allows reading pre- and postconditions nearly like natural language. This allows simply copying these assertions into the method comments.

How can I Use LightContracts

  1. Download the LightContracts DLL
  2. Add a reference to the LightContracts.dll in your .NET project
  3. Insert a "using LightContracts;" statement.
  4. Write your pre- and postconditions directly in the methods
  5. Copy the pre- and postconditions to the method comments to enrich the method documentation for clients of you class


using System.Collections.Generic;
using LightContracts;

namespace LightContractsExamples
	public class TextStorage
		private IDictionary<string,string> texts = new Dictionary<string,string>();
		public bool Contains(string text)
			return texts.ContainsKey(text);
		public int Count
			get{ return texts.Count;}
		/// <summary>
		/// Add text.
		/// Requires.IsNotNull(newText,"newText");
		/// Requires.That(!Contains(newText),"Not Contains({0})",newText);
		/// Ensures.That(Count > 0,"Count > 0");
		/// </summary>
		/// <param name="newText">The text to be added</param>
		public void AddText(string newText)
			Requires.That(!Contains(newText),"Not Contains({0})",newText);
			Ensures.That(Count > 0,"Count > 0");

Last edited Nov 12, 2009 at 9:41 AM by SvenGrand, version 14