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.
- public void LogAction(Action action)
- {
-
- var actionName = "Empty";
- if (action != null && action.Method != null)
- {
- actionName = action.Method.Name;
- }
-
-
- 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.