Blog: Extension Methods

Elegant method parameter validation with Code Contracts support

February 25, 2015, (updated on February 26, 2015), 1 comment, Software Development

Each C# developer knows the drill: Each method parameter has to be validated against null values, wrong value ranges or other contract constraints. When also validating using Code Contracts, the resulting code may take up most of the method body: public void Foo(object a, string b) { Contract.Requires(a != null); Contract.Requires(b != null); Contract.Requires(b != string.Empty); if (a != null) throw new ArgumentNullException("a"); if (string.IsNullOrEmpty(b)) throw new ArgumentNullException("b"); ... } Note: When Code Contracts runtime validation is enabled, the call to Requires may throw an exception and the own code for throwing an ArgumentNullException is not needed. However, often the […] Read more...

Tags: , , , , , ,


  Page 1 of 1