12

I'm a fan of the "fail early" strategy and want to check that methods params have correct values for example. In Java I'd use something like Guava:

checkArgument(count > 0, "must be positive: %s", count);

Is there something similar for .NET?

Sam
  • 7,252
  • 16
  • 46
  • 65
deamon
  • 89,107
  • 111
  • 320
  • 448

4 Answers4

8

What you want to do is Design By Contract.

You should use Code Contracts for defining contracts i.e. Preconditions, post-conditions and invariants for your types\methods in C#.

IMO the best and most comprehensive coverage of code-contracts is here.

Unmesh Kondolikar
  • 9,256
  • 4
  • 38
  • 51
5

Code contracts: http://msdn.microsoft.com/en-us/devlabs/dd491992

Snowbear
  • 16,924
  • 3
  • 43
  • 67
4

Code Contracts are still an add on/not part of the standard Visual Studio install, but they do allow you to express pre and post conditions and object invariants.

Different options are available for enforcing the contracts as compile-time or run-time checks (or both).

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

Take a look at CuttingEdge.Conditions. It allows you to write your preconditions in a fluent manner, as follows:

ICollection GetData(int? id, string xml, IEnumerable<int> col)
{
    Condition.Requires(id, "id")
        .IsNotNull()
        .IsInRange(1, 999)
        .IsNotEqualTo(128);

    Condition.Requires(xml, "xml")
        .StartsWith("<data>")
        .EndsWith("</data>")
        .Evaluate(xml.Contains("abc") || xml.Contains("cba"));

    Condition.Requires(col, "col")
        .IsNotNull()
        .IsNotEmpty()
        .Evaluate(c => c.Contains(id.Value) || c.Contains(0));
}

You need C# 3.0 or VB.NET 9.0 with .NET 2.0 or up for CuttingEdge.Conditions.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • 1
    @daemon - I've been addicted to using CuttingEdge.Conditions -- NuGet that bad boy and u'll never look back :) Takes one sec to NuGet it and 1 second to start using it. Go! Quick! Tick this question then go and get it! -me == fanboi. – Pure.Krome Mar 07 '11 at 12:26