I'm working on a large project where, even with 10s of 1000s of automated tests and 100% code coverage, we're getting a ridiculous number of errors. About 95% of errors we get are NullReferenceExceptions.
Is there any way to enforce null-checking at compile time?
Barring that, is there any way to automagically enforce null-checking in unit tests without having to write the tests for null cases myself?
This isn't a technical solution, but a social one. Simply make it unacceptable in your environment to access a reference type without checking for null when the reference type has been modified in any way by outside code (another method call, etc). Unit Testing doesn't replace good old-fashioned code review.
Defensive programming can only get you so far... maybe its just better to catch the exception and deal with it like any other.
neither of those is possible with C# 3. you would have to use something like Spec#... i think C#4 may have some of that built into it, but i'm not sure about that.
spec#: http://research.microsoft.com/en-us/projects/specsharp
You should look into Code Contracts. The static checker is only available for the higher-end VS editions, but that's basically what you're after.
There are plenty of resources online, and
<plug>
you can also read a prerelease version of the chapter on Code Contracts from the 2nd edition of C# in Depth - download chapter 15 for free.</plug>
(The chapter is slightly out of date with respect to the latest and greatest build of Code Contracts, but nothing huge.)Nope. The compiler cannot determine if the run-time reference variable is pointed to null.
And ruling out null producing statements (sets and returns) isn't enough either. Consider:
1) I think, the Resharper can suggest you to check some critical places in your code. For example, it suggests to add the [null reference check code] and adds it if you allow.
Try it. It will increase your experience if you need, of course.
2) Use "Fail Fast" pattern (or assert, assertions) in your code at the early stage of development application