Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard framework for .NET parameter validation that uses attributes?

Is there a standard framework (maybe part of Enterprise Library... or .NET itself) that allows you to do common parameter validation in method attributes?

like image 406
Eric Schoonover Avatar asked Sep 26 '08 07:09

Eric Schoonover


2 Answers

The Microsoft Enterprise Library has the Microsoft.Practices.EnterpriseLibrary.Validation library/namespace which allows validation using attributes.

like image 126
EggyBach Avatar answered Oct 05 '22 23:10

EggyBach


Microsoft Code Contracts, which are part of .NET Framework since 4.0 CTP and are available for earlier .NET Framework versions as a stand-alone package, allow to specify coding assumptions. This includes specifying pre-conditions which can verify parameters.

An example use for parameter checking would be (copied from Code Contracts documentation):

public Rational(int numerator, int denominator)
{
    Contract.Requires(denominator ! = 0);
    
    this.numerator = numerator;
    this.denominator = denominator;
}

The benefit of using Code Contracts is that it is a library which will be part of future .NET Framework releases, so sooner or later you will have one dependency less in your application.

EDIT: Just noticed that your specifically asking for a library that uses Attributes for argument checking... that Code Contracts does not. The reason why Code Contracts does not use attributes is listed in their FAQ:

The advantage of using custom attributes is that they do not impact the code at all. However, the benefits of using method calls far outweigh the seemingly natural first choice of attributes:

Runtime support: Without depending on a binary rewriter, contracts expressed with attributes cannot be enforced at runtime. This means that if there are preconditions (or other contracts) that you want enforced at runtime, you need to either duplicate the contracts in the code or else include a binary rewriter in your build process. Contract.RequiresAlways serves both as a declarative contract and as a runtime-checked validation.

Need for parsing: Since the values that can be used with custom attributes are limited, conditions end up being encoded as strings. This requires defining a new language that is appropriate for all source languages, requires the strings to be parsed, duplicating all of the functionality the compiler already possesses.

Lack of IDE support: Expressed as strings, there is no support for Intellisense, type checking, or refactoring, all of which are available for authoring contracts as code.

like image 34
Christian Avatar answered Oct 05 '22 23:10

Christian