6
votes

Null reference exceptions are one of the top sources of program failures. Tony Hoare called it his billion dollar mistake. So I'm particularly looking forward to C# 8 and the new nullable reference types feature. I think I've got a pretty good grasp of the feature and what it's going to mean for my code. There is one aspect I'm struggling the get my head around though and that's how default will behave.

Currently in C# default(string) will return null. But when C# 8 comes along then doing something like string x = default(string); should surely give a compiler warning straight off the bat. Seems like this is a bit of a paradox. I'm also wondering if default(string?) will be possible and what would it even return. I guess it would have to be null which just adds to my confusion.

I don't think there has been a preview release of this feature yet, but I was wondering if anyone knows yet how this will be handled.

1
Since string will be an object, the default(string) giving null is pretty much meaningful. - Bharadwaj
And this specific question has been asked and addressed. - Damien_The_Unbeliever
And just in general - C# language design is being done "in the open" over on github. So that's the logical place to search for this kind of information. - Damien_The_Unbeliever
@HimBromBeere - not if you've opted into the nullable reference types feature and declare the variable to not contain nulls, no. - Damien_The_Unbeliever

1 Answers

5
votes

This question is possible to answer now, rather than waiting for C# 8 to be released. C# is now developed "in the open", so just ake yourself over to SharpLab, select the NullabaleReferenceTypes branch and try the code.

It gives a warning CS8600: Cannot convert null to non-nullable reference. as default of a reference type is null and null should not be assigned to the non-nullable string.

If you'd prefer to test a preview in VS2017, a preview plugin is available for the IDE, too.