'Nullable Enable' To Avoid Null Reference Exception

Introduction

 
We have seen unknown null reference in our production code sometimes. To avoid this this common problem, Microsoft has come  up with a new C# 8.0 feature called 'nullable enable'. Enabling this nullable feature in your code will identify all areas where null reference exception can occur and force you to fix it by either adding null check or throwing known exception.
 

Implementation

 
Let's see the below code snippet and understand where the null reference exception can happen. if we miss one in development then it can create an issue in production later. 
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var trainings = TrainingService.GetTrainings();  
  6.   
  7.         foreach (var item in GetTrainingData(trainings))  
  8.         {  
  9.             Console.WriteLine(item);  
  10.         }  
  11.     }  
  12.   
  13.     static IEnumerable<string> GetTrainingData(IEnumerable<Training> trainings)  
  14.     {  
  15.         foreach (var item in trainings)  
  16.         {  
  17.             yield return $" Traning {item.Name} has {item.Cost} with first course {item.Courses[0]}";  
  18.         }  
  19.     }  
  20. }  
  21.   
  22. public class Training  
  23. {  
  24.     public string Name { getset; }  
  25.   
  26.     public string Courses { getset; }  
  27.   
  28.     public string Cost { get;  set; }  
  29. }  
  30.   
  31. public static class TrainingService  
  32. {  
  33.     public static IEnumerable<Training> GetTrainings()  
  34.     {  
  35.         var trainings = new List<Training>();  
  36.         trainings.Add(new Training() { Name = "c# 8.0", Cost = "$20" });  
  37.         trainings.Add(new Training() { Name = "JS", Cost = "$40", Courses = "BasicData type, loops etc" });  
  38.   
  39.         return trainings;  
  40.     }  
  41. }  
if you notice in GetTrainingData() to get the first element of Course, this could create an exception here if Course is null. But currently compiler does not detect this hidden null item and informs you to take care.
 
if you execute this code, you will get the null reference.
 
C# 8.0 ('Nullable Enable') To Avoid Null Reference Exception
 

C# 8.0 Nullable enable 

 
C# 8.0 has come with new feature i.e. 'nullable enable', enabling this feature will allow compiler to verify all properties and parameters in your code and track where null reference is possible and inform you to fix it. Let's enable nullable in your code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. #nullable enable  
  4.   
  5. namespace TrainingModule  
  6. {  
  7.     class Program  
  8.     {  
  9.      }  
  10. }  
Enabling this feature will show you all possible errors (non-nullable property is uninitialized) in your code to fix,
  1. Initializing all default properties in constructor
  2. If property is not initialized and is a candidate for null then it will ask to add null check wherever it used, similar to my code snippet where I have placed in GetTraining method.
Final code looks like below after adding nullable feature.
  1. using System;  
  2. using System.Collections.Generic;  
  3. #nullable enable  
  4.   
  5. namespace TrainingModule  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             var trainings = TrainingService.GetTrainings();  
  12.   
  13.             foreach (var item in GetTrainingData(trainings))  
  14.             {  
  15.                 Console.WriteLine(item);  
  16.             }  
  17.   
  18.             Console.ReadKey();  
  19.         }  
  20.   
  21.         static IEnumerable<string> GetTrainingData(IEnumerable<Training> trainings)  
  22.         {  
  23.             foreach (var item in trainings)  
  24.             {  
  25.                 yield return item.Courses != null ? $" Traning {item.Name} has {item.Cost} with first course {item.Courses[0]}"  
  26.                     : $" Traning {item.Name} has {item.Cost}";  
  27.             }  
  28.         }  
  29.     }  
  30.   
  31.     public class Training  
  32.     {  
  33.         public Training(string name, string cost)  
  34.         {  
  35.             Name = name;  
  36.             Cost = cost;  
  37.         }  
  38.   
  39.         public string Name { getset; }  
  40.   
  41.         public string? Courses { getset; }  
  42.   
  43.         public string Cost { get;  set; }  
  44.     }  
  45.   
  46.     public static class TrainingService  
  47.     {  
  48.         public static IEnumerable<Training> GetTrainings()  
  49.         {  
  50.             var trainings = new List<Training>();  
  51.             trainings.Add(new Training("c# 8.0""$20"));  
  52.             trainings.Add(new Training("JS""$40") { Courses = "Basic, Data type, loops etc" });  
  53.   
  54.             return trainings;  
  55.         }  
  56.     }  
  57. }  

Conclusion

 
Here, we learned how to use nullable feature of C# 8.0 in your code and avoid null reference exception during development time.
Author
Ashutosh Gupta
382 3.9k 968.1k