deamon
deamon

Reputation: 92447

Checking preconditions in .NET

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?

Upvotes: 12

Views: 4154

Answers (4)

Steven
Steven

Reputation: 172666

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.

Upvotes: 1

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

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.

Upvotes: 8

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239694

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).

Upvotes: 4

Snowbear
Snowbear

Reputation: 17274

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

Upvotes: 5

Related Questions