How do I enforce null checking?
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.
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.)
100% code coverage means nothing.
It is a false sense of security.
The only thing you're measuring is that you're executing all the lines of code.
Not:
- That those lines of code are all the lines of code that should've been there
- That those lines of code are operating correctly (are you testing all edge cases?)
For instance, if your procedure to deal with a fire contains 1 step "run out of the building", then even if that happens in 100% of the cases, perhaps a better procedure would be to "alert the fire department, try to stop the fire, then run out if all else fails".
There is nothing built into C# that will help you with this without you specifically going in and adding code, either code contracts (.NET 4.0) or specific IF-statements (<4.0).
C# 8 has introduced Non-nullable reference types.
A .Net project can be modified to have the Nullable option enabled:
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
The compiler will be able distinguish
string
andstring?
NonNullableClass
andNullableClass?