Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable Reference Types with C# 8

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.

like image 585
pmcilreavy Avatar asked Feb 08 '18 08:02

pmcilreavy


People also ask

What are nullable reference types?

Nullable reference types aren't new class types, but rather annotations on existing reference types. The compiler uses those annotations to help you find potential null reference errors in your code. There's no runtime difference between a non-nullable reference type and a nullable reference type.

What are C# nullable types?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false .

Can we create nullable type based on reference type?

Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type.

Should I use nullable reference types?

Although using nullable reference types can introduce its own set of problems, I still think it's beneficial because it helps you find potential bugs and allows you to better express your intent in the code. For new projects, I would recommend you enable the feature and do your best to write code without warnings.


1 Answers

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.

like image 50
David Arno Avatar answered Oct 14 '22 18:10

David Arno