Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to assert pre-condition and post-condition of arguments and values in .NET?

I have been thinking about design by contract lately and I was wondering what people think is the best way to assert pre-condition and post-condition of values in .NET? i.e. validating argument values to a method.

Some people recommend Debug.Assert while others talk about using an if statement plus throwing an exception. What are the pros and cons of each?

What frameworks are available that you recommend?

like image 255
James Newton-King Avatar asked Mar 02 '23 06:03

James Newton-King


2 Answers

We'll eventually use Code Contracts when .NET 4.0 ships. However, in our production code right now we have had great success with a "Guard" class along with common way to generate exceptions.

For more details, see my post about this.

like image 145
Jeff Moser Avatar answered Mar 04 '23 14:03

Jeff Moser


Another option is Spec#.

Spec# is an extension of the object-oriented language C#. It extends the type system to include non-null types and checked exceptions. It provides method contracts in the form of pre- and postconditions as well as object invariants.

like image 22
Cameron MacFarland Avatar answered Mar 04 '23 15:03

Cameron MacFarland