views:

1640

answers:

6

I'm terribly tired of checking all my arguments for null, and throwing ArgumenutNullExceptions when they are.

As I understand it, C# 4.0 enables some design by contract constructs. Will it be possible to specify that a method will not accept null arguments in C# 4.0?

Also, is there anything I can do in the meantime (maybe an attribute?) to avoid this monotonous task of checking for null and throwing?

+3  A: 

You can create a NotNull<T> generic class that helps, but there are some side effects. See Robert Nystrom's blog post.

orip
A: 

Try this library. It lets you do transparent DbC in any .NET language. Enjoy!

plaureano
+2  A: 

Not sure about native DbC constructs in C# 4.0 but Microsoft is going to release cross-language Contracts library.
You can download version for MSVS2008 here.

aku
+1  A: 

As an alternative to the already given answers, it is worth looking into the Null Object design pattern.

The essence of this design pattern is that once the "null object" is created, there is no further need to perform any checks for null and the methods of the null object implement the behavior desired whenever a null (otherwise) would have been passed vs a reference to a "real object".

This design pattern does not depend on C# 4.0 and in fact can be easily implemented in almost any OO programming language.

Dimitre Novatchev
It's a great pattern, but it doesn't stop callers from passing actual null values.
Daniel Earwicker
+4  A: 

Rick Brewster describes a good solution for concise, declarative style parameter checking in this post,

http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/

Avoids use of reflection (drawback of DbC) and creates no overhead for non-exceptional code path.

Like how he uses extension methods to allow what appears to be instance method calls on null objects. Very clever bit of coding IMO.

If you are sold on DbC, Google Spec# and PostSharp.

Matt

Matt Randle
A: 

I have just started using Code Contracts its a new feature in C# 4.0 you need to download an addin from MS to allow you to see it in your project settings. Details here -> http://research.microsoft.com/en-us/projects/contracts/