Null Conditional Operator in C# 6.0 or Safe Navigation of Objects

C# 6.0 includes a new null-conditional operator (sometimes called the Safe Navigation Operator):

In previous versions null checking for any kind of objects manually we need to write if condition then we need to write our required properties or else we need to write our business logic.

  1. If(Object != null)  
  2. {  
  3.     If(Object.User != null)  
  4.     {  
  5.         return object.User.Name;  
  6.     } Else  
  7.     {  
  8.         return null;  
  9.     }  
  10. }  
Another way of checking null condition using ternary operator (Single line if statement) as follows:
  1. return object!=null? (object.user!=null?object.User.Name:null):null;  
Now In c# 6.0 Microsoft is coming up with a new null-conditional operator that helps you write these checks more succinctly as follows
  1. return object?.user?. Name;  
Note: If object is null then it won’t navigate to nested object.
Ebook Download
View all
Learn
View all