Code -> Break -> Fix -> Blog

C# 6.0 : Null conditional Operator (?.)

1 Comment

Problem : Say we have an Employee class with EmpID, Name & PhoneNo properties.

 internal class Employee
 public int EmpID { get; set; }
 public string Name { get; set; }
 public string PhoneNo { get; set; }

Now if we want to print PhoneNo, we need to have a null check for the employee object as well as for PhoneNo property.

if (employeeObject != null && employeeObject.PhoneNo != null)

To avoid these checks C# 6.0 introduces a new operator called Null conditional (?.) operator.

Also known as Elvis operator.

The code is now much simpler with C# 6.0

WriteLine(employee?.PhoneNo ?? "No Phone Number available");

Oh man!!! This will surely reduce lots of null checks statements.

Also, the ?. operator makes working with Events much simpler.

For C# version < 6.0:

if (OnPhoneNoChanged != null)
 OnPhoneNoChanged(this, e);

C# 6.0, makes it simpler

OnPhoneNoChanged?.Invoke(this, e);

Let me know your thoughts.


Twitter Logo


One thought on “C# 6.0 : Null conditional Operator (?.)

  1. Pingback: New Features of C# 6.0 | Bhavya

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s