Checking preconditions in .NET
Asked Answered
B

4

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?

Basicity answered 7/3, 2011 at 9:8 Comment(2)
+1 for being a fan of the "fail early" strategy. What is the earliest version of the .NET Framework that you need to target?Importunate
Target platform is .NET >= 3.5.Basicity
G
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.

Grope answered 7/3, 2011 at 9:43 Comment(0)
O
5

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

Opinion answered 7/3, 2011 at 9:10 Comment(0)
F
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).

Flounder answered 7/3, 2011 at 9:11 Comment(0)
S
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.

Smacking answered 7/3, 2011 at 9:37 Comment(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.Fontes

© 2022 - 2024 — McMap. All rights reserved.