Code Contracts in .NET 4.0, no joy for non-nullable reference types fans?-Collection of common programming errors
I think you’re correct about this. Non-nullable reference checking at compile time was the killer feature I was waiting for in Code Contracts, and it isn’t really there.
For those wondering what this means, consider an analogy with value types. They were not nullable originally, but now they are if you put a question mark after the type name:
int? n;
For consistency it would be ideal if the same was true of reference types. But that would break all existing C# programs and so isn’t an option. In the research language Spec# they went with using an exclamation mark suffix to mean non-nullable:
string! s = "Hello";
As with ordinary value types, the compiler statically checks that a string! variable is not used on any code path before it has been initialised (I believe Spec# requires declaration and initialization to occur in the same statement).
It also bans the assignment of null to that variable.
And of course, it bans the assignment of an ordinary string to a string!. So how do bridge the gap between the two kinds of type? By writing a check:
string x = GetStringFromSomewhere();
if (x != null)
s = x; // okay because compiler sees null check
The sad truth is that the majority of reference variables in most programs are likely to be non-nullable if the program is correct. Nullable variables are in the minority. And yet they are the default.
Another bad idea from the 1960s!