Proposed New Features in C# 8: nullable reference types

C# 8’s new proposed enhancements

In C# 8 following language enhancements are proposed:

  • Nullable Reference Types
  • Async streams
  • Default interface implementations
  • Extension everything

In this article, we will look into one of the proposed enhancement: Nullable Reference Types

Nullable Reference Types

We already have syntax to specify nullable value-types that can be assigned the value of null.

T? where T is a value type.

In C# 8’s proposed language enhancements, it is planned to extend that to reference-types as well.

T? where T is a reference type.

So, now with C# 8’s proposed changes, we can specify whether the reference-types is intended to be null or not.

reference-types not intended to be  null:

string address; // specifies that address is not intended to be null.
address = null; // this will give warning.

reference-types intended to be  null:

string? address; // specifies that address can be null.
address = GetAddress();

Now, if we try to get length of “address”, without any check for null:

int length = address.Length;

compiler will give warning, if flow analysis cannot establish a non-null situation. To fix that we need to place a check for null before accessing the Length property.

int length = address?.Length ?? 0;

Places where developer is sure that the value can not be null but compiler (flow analysis) was not able to figure it out & still gives warning, he can use the “dammit” operator (x!).

int length = address!.Lenght;

for telling compiler that “address” will not be null.

Will share full working sample codes in my future posts on above enhancement once C# 8 enhancement are released. I am looking forward to see Nullable Reference Types in action.

Happy Coding !!!

You may also like...

1 Response

  1. Shanon says:

    It works very well for me

Leave a Reply

Your email address will not be published. Required fields are marked *