A Proposal for Non-Nullable Types in C#
If unexpected values are the problem, then we should strive to eliminate them. Null is almost never expected, but the type system forces us to act as though it is. -- Craig
In one way or another this statement has been uttered by countless .NET developers over the years. Yet fixing it isn’t as easy just simply slapping an attribute or other decoration on the variable. One of the more daunting challenges is how to handle default<T> when T is a non-nullable reference type. Craig writes,
The fundamental problem here is an assumption deeply ingrained into C#: the assumption that every type has a default value. Consider: if T doesn’t (or might not have) a default value then the compiler has nothing to use when evaluating default(T), initializing a field of type T, or initializing the items in a new array of T. This is a problem when it comes to non-null reference types because, although some reference types have a decent non-null default value (e.g. the default non-null String could be the empty string), most do not. Consider: what is the default non-null value of IEnumerator<int>? IObservable<bool>? UserControl? NetworkStream? The simple answer is that they don’t have one. The “best” you can do is give a mock instance that fails if you try to use it… but we already have that and it’s called null.
In this article titled Non-Nullable Types vs C#: Fixing the Billion Dollar Mistake, Craig introduces two new concepts:
- T! to indicate the type T is non-nullable. This is used on normal types as well as type parameters.
- withdefault(T) which turns non-nullable reference type parameters into their nullable counter-part
If you need to build a private field or array, you make them of type withdefault(T) instead of type T. Then when reading the field or array, you cast it back to the non-nullable type T. This cast itself is unsafe and may throw an exception if improperly constructed, but developers can rely on anything downstream of it being non-null. The ramifications of this are best explained via the examples in Craig’s article.
If you are interested in this topic you can vote for non-null reference types on UserVoice.
Brandon Holt, Preston Briggs, Luis Ceze, Mark Oskin May 21, 2015
Kai Kreuzer, Olaf Weinmann May 21, 2015