Page 20 - MSDN Magazine, February 2018
P. 20

ESSENTIAL .NET
C# 8.0 and Nullable
Reference Types
Mark Michaelis
Nullable reference types—what? Aren’t all reference types nullable?
I love C# and I find the careful language design fantastic. None- theless, as it currently stands, and even after 7 versions of C#, we still don’t have a perfect language. By that I mean that while it’s reasonable to expect there will likely always be new features to add to C#, there are also, unfortunately, some problems. And, by prob- lems, I don’t mean bugs but, rather, fundamental issues. Perhaps one of the biggest problem areas—and one that’s been around since C# 1.0—surrounds the fact that reference types can be null and, in fact, reference types are null by default. Here are some of the rea- sons why nullable reference types are less than ideal:
• Invoking a member on a null value will issue a System.Null- ReferenceException exception, and every invocation that
results in a System.NullReferenceException in production code is a bug. Unfortunately, however, with nullable reference types we “fall in” to doing the wrong thing rather than the right thing. The “fall in” action is to invoke a reference type without checking for null.
• There’s an inconsistency between reference types and value types (following the introduction of Nullable<T>) in that value types are nullable when decorated with “?” (for exam- ple, int? number); otherwise, they default to non-nullable. In contrast, reference types are nullable by default. This is “normal” to those of us who have been programming in C# for a long time, but if we could do it all over, we’d want the default for reference types to be non-nullable and the addi- tion of a “?” to be an explicit way to allow nulls.
• It’s not possible to run static flow analysis to check all paths regarding whether a value will be null before dereferencing it, or not. Consider, for example, if there were unmanaged code invocations, multi-threading, or null assignment/ replacement based on runtime conditions. (Not to mention whether analysis would include checking of all library APIs that are invoked.)
• There’s no reasonable syntax to indicate that a reference type value of null is invalid for a particular declaration.
• There’s no way to decorate parameters to not allow null. As already said, in spite of all this, I love C# to the point that I just accept the behavior of null as an idiosyncrasy of C#. With C#
The C# Nullable Reference Types Preview is pre-release software. The features and behavior may change without notice.
This article discusses:
• The problem with nullable reference types
• Four improvements to C# 8.0 to fix nullable references • C# 8.0 nullable reference type syntax
• Further enhancements in C# 8.0
Technologies discussed:
The Nullable Reference Type Design for C# 8.0
16 msdn magazine


































































































   18   19   20   21   22