Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
deamon Avatar asked Mar 07 '11 09:03

deamon


People also ask

What is precondition C#?

Requires method. Preconditions specify state when a method is invoked. They are generally used to specify valid parameter values. All members that are mentioned in preconditions must be at least as accessible as the method itself; otherwise, the precondition might not be understood by all callers of a method.

What are contracts C#?

Abstract: Code Contracts API includes classes for static and runtime checks of code and allows you to define preconditions, postconditions, and invariants within a method. The Contracts class is found in the System. Diagnostics namespace.


2 Answers

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.

like image 59
Unmesh Kondolikar Avatar answered Nov 09 '22 06:11

Unmesh Kondolikar


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

like image 25
Snowbear Avatar answered Nov 09 '22 05:11

Snowbear