Conditional Access in C# 6.0

This feature is very helpful to use in a scenario like to get the property value from the object only if object is not null.

For Example, you are considering delegate Action as the parameter to any of the method, You want to get the name from the Action Method only if Action is not null and Action.Method is not null.

You can easily get an idea by just looking the below code.

  1. public void LogAction(Action action)  
  2. {  
  3.     //Before C# 6.0  
  4.     var actionName = "Empty";  
  5.     if (action != null && action.Method != null)  
  6.     {  
  7.         actionName = action.Method.Name;  
  8.     }  
  10.     //C# 6.0  
  11.     var actionName = action?.Method?.Name ?? "Empty";  

As per the above code in C# 6.0, action is not null and Method is not null then only "Name" property value is assigned otherwise "Empty" value will be assigned.