Sunday, May 20, 2018

Non Nullable Reference Types in Upcoming C# 8

NON-NULLABLE Reference Types

In today's blog post, I will be discussing one of the new & exciting feature of upcoming C#8. The work is currently under way. This is more of a sneak preview :)

Currently, whenever we have a reference type, it's always nullable by default. If I don't assign any value to a reference type, it defaults to null. Furthermore, as a programmer, there is no way to specify that for this specific reference, I want to disallow nulls. As a result, these nulls do sneak into our applications and cause the famous Null reference exceptions. Tony Hoare, the guy who invented Null, called it his billion dollar mistake. I am pretty sure, it has costed more than that by now!

This feature attempt is to reduce these null reference exceptions. The biggest hurdle is, if C# 8 disallows nulls on reference types completely, then it's not backward compatible. So this feature is going to be an opt-in feature. The idea is that slowly people will adopt this feature and as more and more code becomes compatible to this feature, they can completely turn off the switch for default nulls sometime in future.

Non Nullable reference Type C# 8
The feature will provide the ability to the programmer to make the decision consciously whether to allow nulls or not to reference types, similar to the way we do it for primitive types. For e.g. when I say


int? x; // explicitly nullable

If I don't put "?" then nulls are disallowed.

So using similar syntax, the plan is, if you opt in the feature for not allowing reference types to be null, then any code like this will throw a warning:


string str = null; //Warning

Now, to fix this, you have 2 options:
Either, you will have to explicitly make it nullable like this:


string? str = null;

OR

Assign it something other than null and expect that null will never be assigned to this reference.

string str = "text";

This way you are consciously making decision of allowing or disallowing nulls for these reference types too.

With that said, with the last syntax above, there are ways to still assign nulls to this reference indirectly at run time and still get Null reference exception. Not everything can be known at compile time. But the idea is that the exception will become less common.

CONCLUSION

I think this a great step by C# team to improve the code quality and reduce the number of run time exceptions. With each and every version, the C# language is moving towards better. Happy coding :)