Well, maybe not a totally ‘no’ NullReferenceException, but a whole lot less than now. Well, yeah, I had to catch your attention somehow :P. But anyway, have you heard those rumors about C# 8, how amazing it is going to be and how hard Microsoft is working on the release…? If not, you definitely should read this post! Because the promised changes sound really good and will be a must-to-know quite soon.
So today I wanted to write about one of the “louder” planned features – nullable reference types. Yes, you read it right. And yes, all the reference types we already have in C# are actually… nullable. Yeah, makes no sense, yeah, what a bullsh… No! Wait!
tl;dr; The plan is to make all the reference types not nullable by default.
And if you decide you want an object of some reference type to be nullable, you just add a “?” sign at the end of a type name. Just like we do now with the primitives. Let’s look at the below extremely sophisticated code :P.
In C# 7.x:
System.IO.FileInfo? xx = null;
System.IO.FileInfo yy = null;
Now let’s spend 5 seconds on analyzing this code. Do you think it will compile?
Of course, the answer is ‘NO’! Visual Studio will show the below error:
The type ‘FileInfo’ must be a non-nullable value type in order to use it as parameter ‘T’ in the generic type or method ‘Nullable<T>’
So, the compiler says that making already nullable type as ‘literally written’ nullable makes no sense. Well, this time the machine wins!
Good or bad change?
I know, my opinion doesn’t matter ? and Microsoft will do what they planned, but… I would say, the question is quite tricky. Making all the types in our app non-nullable by default seems to be an excellent idea. It will make our apps less vulnerable to NullReferenceException, we will have to write less if-statements to check whether an object is null or not etc.
On the other hands, we all have tons od code written in older versions of C# and it can cause some troubles. Of course, by default, C# 8 will be set only in brand new project templates, so there is no worry… Assuming that nobody will upgrade C# version in an existing project… or there is no project’s language version set to ‘C# latest version’ ?. In case, you are curious what do you have in your projects, here is how you can check it . By the way, I believe that Visual Studio won’t make upgrades to C# 8 happen silently. That would be unfair and Microsoft is for sure aware of that… Is it? 😉
At the very end, there is another problem that I think may be annoying. What if you spend a few months in a project written in the newest C# and then you have to come back to some old code, written in C# 7.3 (or even older)? Will you still remember to check if objects are null or not? Because you will have to!
What is your opinion on this subject?