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.

  • 1
    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. Commented May 30, 2011 at 5:18
  • 1
    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
    Commented May 30, 2011 at 5:22
  • 1
    @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.
    Commented May 30, 2011 at 12:20
  • @Kevin: The former: null is never possibly returned.
    – Peter K.
    Commented May 30, 2011 at 12:21
  • 1
    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
    Commented May 30, 2011 at 22:30

1 Answer 1


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.

  • Thanks! That gives an interesting addition we hadn't thought about.
    – Peter K.
    Commented Jun 2, 2011 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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