简体   繁体   中英

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.

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 .

I was curious, too.

default(string?) // no warning, returns null when nullable reference types are enabled
default(string) // warning CS8603 when nullable reference types are enabled, but it compiles successfully and actually, it returns null, too.

That means: In the following scenario, string a is not nullable, but it is actually null.

string MyMethod(){
    return default;
}
string a = MyMethod();

So, if MyMethod comes from a foreign library with NullableReferenceTypes enabled, it's still possible that the library developers messed something up and that the method returns null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM