Saturday 19 December 2015

Null-Conditional Operator in C# 6


C# 6 introduced a Null-Conditional operator which makes null checks more concise. If object on which it is applied is null, it will immediately return null, if not, it will return result of the operation applied on that object (invoking method, property...onto which other operations might be chained). Instead of writing:


var personName = person == null ? null : person.Name;


...we can write:


var personName = person?.Name;


?. is a first form of this operator. The other one is ?[] and is used when accessing array elements. Instead of performing null check of the array and then accessing its elements, we can now put those two operations in a single expression:


var arr = new string[]{"abc" , "def"};
var arr0 = arr?[0]; // "abc"
arr = null;
arr0 = arr?[0]; // null


This operator comes very handy when raising events. Before, we would write:


public event Action SomeEvent;
private void OnSomeEvent()
{
   if (SomeEvent != null)
   {
      SomeEvent.Invoke();
   }
}


...but now we can write:


public event Action SomeEvent;
private void OnSomeEvent()
{
   SomeEvent?.Invoke();
}


No comments: