C# 8.0 - Experimenting With Non-Nullable Reference Type Using Visual Studio 2017

Nullable Reference Type is one of the most popular upcoming features of C# which may be released with C# 8.0. However, since C# 8.0 has not been released yet and the development is going on, so till the final release, its behavior may be a little bit different than the current behavior explained in this article.

C# 8.0

Many discussions are going on in developer’s communities about C# 8.0 Nullable reference type, and most of us are referring it to a breaking change. However, in my opinion, it is a significant change but not a breaking change.

By using this feature, a developer can write more optimized code and get a very few number of null reference exception. Using Nullable reference type does not guarantee you that you will never get a null reference exception but its probability can be minimized.

Topics covered in this article,

  1. Why is it a significant change but not a breaking change?
  2. Checking for Null reference before using a reference type variable
  3. Non-nullable and nullable reference type with C# 8
  4. Assigning default value to Non-nullable reference type
  5. Warning: Possible dereference of a null reference
  6. Getting warning message while trying to assign a null value to non-nullable reference type
  7. Treating warnings as errors
  8. You do not need to change your existing code
  9. Using (non) nullable Reference type with null-coalescing operator (??) and null-conditional operator (?. and ?[] )
  10. Installing Null-reference preview with Visual Studio 2017
  11. Un-installing Null-reference preview from Visual Studio 2017
Why is it a significant change but not a breaking change?

It is not a breaking change because it is not going to break anything. You can run your existing code smoothly without making a single bit of change and everything will work perfectly fine.

It will be completely optional and configurable, and if you do not want to change your code, then there is no need to change it. Let’s have a look what it is, then we can discuss its pros and cons later.

Till C# 7.2, we can write a class and its properties as follows.

  1. internal class User  
  2.     {  
  3.         public string UserId        { get; set; }    
  4.         public string Name          { get; set; }     
  5.         public string FacebookUrl   { get; set; }   
  6.         public string TwitterUrl    { get; set; }  
  7.   
  8.         public void Display()  
  9.         {  
  10.             WriteLine($"User Id is : {UserId.Length} character(s) long");  
  11.             WriteLine($"User name : {Name.ToUpper()}");  
  12.             WriteLine($"Facebook URL : {FacebookUrl.Trim()}");  
  13.         }  
  14.     }  

The above code snippet will get compiled perfectly but you may end-up with a null reference exception at runtime.

Now, call Display () method of User class.

  1. class Program  
  2.     {  
  3.         static void Main(string[] args) => new User().Display();  
  4.     }    

You will get a Null reference exception for all the 3 lines of Display() method. Following is the screenshot of the same.

C# 8.0

Checking for Null reference before using a reference type variable

Null reference exception can be by avoided by checking for the null value each time before using it. Following is the code snippet for the same.

  1. public void Display()  
  2.         {  
  3.             WriteLine($"User Id is : {UserId?.Length ?? 0} character(s) long");  
  4.             WriteLine($"User name : {Name?.ToUpper()}");  
  5.             WriteLine($"Facebook URL : {FacebookUrl?.Trim()}");  
  6.         }  

However, you cannot force every developer to check it for null reference before using it each time or even if you may forget to check it accidentally which can cause the null reference exception.

Non-nullable and nullable reference type with C# 8

In C# 8, we can make a reference type nullable or non-nullable intentionally, thus properties of User class can be written as,

  1. internal class User  
  2.     {  
  3.         public string   UserId          { get; set; }   //non-nullable reference type  
  4.         public string   Name            { get; set; }    //non-nullable reference type  
  5.         public string?  FacebookUrl     { get; set; }   //nullable   
  6.         public string?  TwitterUrl      { get; set; }   //nullable   
  7.     }  

Screenshot

C# 8.0

We are making the required fields Non-nullable and other fields as nullable. The above code snippet will give a warning because non-nullable properties are uninitialized. Following is the screenshot of the same.

C# 8.0

Assigning default value to Non-nullable reference type

Default values can be assigned to non-nullable reference type to avoid null reference exception. Following is the code snippet for the same.

  1. public User()  
  2.  {  
  3.      UserId =    Empty;  
  4.      Name =      Empty;              
  5.  }     

As soon as default values are assigned to non-nullable reference type variable, the warning messages will be removed. Following is the screenshot of the same.

C# 8.0

I am assigning an Empty value just for an explanation, but we can create a parameterized constructor as well to force the user to pass it as a parameter while creating a new instance.

Warning: Possible dereference of a null reference.

Let’s have a look at the below code snippet,

  1. static void Main(string[] args)  
  2.         {  
  3.             User user = new User();  
  4.             WriteLine($"FB URL Length: {user.FacebookUrl.Length}");  
  5.         }  

C# 8.0

Moreover, if you are ignoring this error, you may end up with null reference exception as shown in the below screenshot.

C# 8.0

Getting warning message while trying to assign a null value to non-nullable reference type

Till now, I talked a lot about default value initialization for a non-nullable reference type. Now I am going to assign null values to a non-nullable reference type.

Directly assigning the null value

user.UserId = null;

Assigning a nullable string to non-nullable string

user.Name = userName;

C# 8.0

As you can see in the above screenshot that I am assigning null values for “UserId” and “Name” properties directly or indirectly and in both cases, I am getting a warning message.

Treating warnings as errors

If I am assigning a null value directly or there is a possibility of null reference assignment for a non-nullable reference type, then it gives warning messages. However, if you would like to minimize the probability of exception and make your code defensive, then you can treat these warning messages as errors. Following is a screenshot of the reference if someone is new to Visual Studio and does not aware of this setting.

C# 8.0

You do not need to change your existing code

It is completely optional and configurable, and if you do not want to change your code, then there is no need to change your code. Your existing application will work perfectly fine without making a single bit of change.

However, if you would like to make your code more optimized or reduce the probability of null reference exception, then you can go for it.

Using (non) nullable Reference type with null-coalescing operator (??) and null-conditional operator (?. and ?[] )

If your reference type code is already well optimized and using null-coalescing operator (??) and conditional operator (?. and ?[] ) then you do not need to worry about it. It will work perfectly fine with nullable reference type and non-nullable reference type in C# 8.0.

  1. //using null-coalescing operator (??)  
  2. WriteLine($"{Name?? "no data found" }");  
  3.   
  4. //using conditional operator (?.)  
  5. WriteLine($"{Name?.ToUpper() ?? "no data found" }");  
  6.   
  7. //using conditional operator (?[]) with Indexes  
  8. WriteLine($"First Item: {Items?[0]}");  

Installing Null-reference preview with Visual Studio 2017

If you are excited about new features and you would like to experiment these features then following is the steps to use it with Visual Studio.

Warning - Install it at your own risk, and your system might get unstable after this installation.

  1. Please make sure that you are having the latest version of Visual Studio 2017 (Visual Studio 15.5 Preview 4 or later).
  2. Create a system restore point before proceeding so that you can restore your machine in case of an issue.

    C# 8.0

    C# 8.0

  1. Download Roslyn_Nullable_References_Preview.zip from here.
  2. Extract the downloaded zip file.
  3. Run “install.bat” from the zip root folder.

Please make sure that all the instances of the Visual Studio are closed before executing this batch file.

Warning: This a batch file so please run it at your own risk.

C# 8.0

Once the batch starts executing it will make many changes on your machine. Following is a screenshot of the same.

C# 8.0

It will get closed once installation completes. Now, open Visual Studio 2017 and start experimenting it.

Un-installing Null-reference preview from Visual Studio 2017

Go to the root folder (the same folder from where you have executed the file “install.bat”) and execute the batch file “uninstall.bat”. You may need to run “uninstall.bat” file to uninstall it properly.

If you would like to explore more about latest features of C#, you can go through these articles.

  1. C# 7.2 - In Parameter and Performance
  2. C# 7.2 New Features with Visual Studio 2017
  3. C# 7.0 And C# 7.1 New Features - Part Two
  4. Expression Bodied Indexers and Operators with C# 7
  5. Understanding ref and out With C# 7
  6. Top 10 New Features of C# 7 With Visual Studio 2017


Recommended Free Ebook
Similar Articles