Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

We are implementing some web services, and need to ensure that some of our methods always return non-null values.

We've investigated two ways of doing this:

Both approaches work, but I'm wondering whether there are any other approaches that we should consider.

How would you enforce non-null return values?

Looks like there was a similar question on SO, and Jon Skeet recommends the Code Contract approach.

share|improve this question
It's been years sice I've used C# seriously at all, but why would you need to enforce returning non-null values? Generally, null is a perfectly valid return value. – Demian Brecht May 30 '11 at 5:18
Are you looking for a way to ensure that null is never possibly returned, or a way to enforce that null return values are treated as runtime errors? – Kevin Hsu May 30 '11 at 5:22
@Demian: null is certainly a valid value for objects. The trouble is that, we want to completely avoid System.NullReferenceExceptions in the receivers of the null. – Peter K. May 30 '11 at 12:20
@Kevin: The former: null is never possibly returned. – Peter K. May 30 '11 at 12:21
Providing you have the tooling available I would definitely go with code contracts. You can then use static analysis to find/eliminate possible null references - pretty much any other approach will only help you at runtime (and obviously contracts will give you that too). – FinnNk May 30 '11 at 22:30
up vote 2 down vote accepted

If you can be 100% certain that there will always be a valid value to return, then the code contracts method makes perfect sense, and you can go on your way.

Now, if there is a possibility of a situation where the method might not have a valid value to return, then you can still use the code contract method and implement the null object pattern. The issue with the pattern is that you still have to, kind of, check for null but the client will never get a NullReferenceException.

share|improve this answer
Thanks! That gives an interesting addition we hadn't thought about. – Peter K. Jun 2 '11 at 19:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.