What’s new in C# 6 Part Two

The days of having to continuously check for null values are coming to an end with C# 6. The next release of the language will bring us a Null Conditional Operator (?.)

Consider this User class:

public class User {
 public int ID { get; set; } 
 public string FirstName { get; set; } 
 public string LastName { get; set; } 
 public List<string> Hobbies { get; set; }
 }

Currently, if we need to check if the user has hobbies, we will have to check if the user is not null, check if Hobbies property is not null then check if the hobbies count is greater than zero.

var user = CreateUser(1); 
var hasHobbies = user != null && user.Hobbies != null && user.Hobbies.Count > 0;

With C# 6, we can perform the same task using the null conditional operator (?.)

var user = CreateUser(1); var hasHobbies = user?.Hobbies?.Count > 0;

The magic here happens at the compiler level, decompiling this code will yield code similar to the following snippet:

User user = Program.CreateUser(1);
 int? nullable1;
 if (user == null)
 {
 nullable1 = new int?();
 }
 else 
{
 List<string> hobbies = user.Hobbies; 
nullable1 = hobbies != null ? new int?(__nonvirtual (hobbies.Count)) : new int?();
 }
 int? nullable2 = nullable1; 
int num = 0;
 bool flag = nullable2.GetValueOrDefault() > num && nullable2.HasValue;

The Null Conditional Operator helps us write less code without sacrificing readability.

Comments are closed