|
17 Apr 2015 by Charlie
The New ?. Operator in C# 6
c#
The ?. OperatorNull Propagation or the ?. operator, is a new operator in C# 6.0 which allows us to reduce the code required for null checks in an invocation chain. So the following code var roleName = userManager.CurrentUser == null ? null : (userManager.CurrentUser.GetRole() == null ? null : userManager.CurrentUser.GetRole().Name);can be re-written simply as below using the ?. operator. var roleName = userManager.CurrentUser?.GetRole()?.Name;roleName will be null if any of CurrentUser, GetRole() or Name is null. As you can see, the code is shorter and the intent is immediately clear with ?. operator. Infact, the first statement calls the GetRole() function twice, while with ?. it gets called only once. You have to add more code to save the result from GetRole() into another variable to avoid this, if you are not using the ?. operator. Before we explore further, play around a bit with Null Propagation using the snippet compiler below:
Value Types And Null PropagationWe know that return type for the function String.Equals() is bool. What do you think about the following code, would it compile? Try it:
The code does not compile and gives a compiler error: "Cannot implicitly convert type 'bool?' to 'bool'". You might have expected this, as the statement str?.Equals("x") has to return null if str is null and a bool otherwise. So for all such statements which return a value type, the return type for the statement gets converted into the corresponding nullable type. Combining it with the ?? operator for more magicYou can use ?? operator for cases when the statement is evaluated to null to provide a default behavior. e.g. var role = userManager.CurrentUser?.GetRole()?.Name ?? "No Role";If any of CurrentUser, GetRole() OR Name is null, it will return "No Role". Try writing the same code without ?. operator. Using ?. with delegatesAt first it may seem we cannot use null propagation with delegates e.g. following is invalid //Invalid Code var result = someDelegate?(p);However you can achieve this as follows: var result = someDelegate?.Invoke(p); As you can see Null Propagation operator is pure syntactic sugar and you are unlikely to replace every . with ?., but in places where it is useful it is immensely valuable as it provides clarity, conciseness and clearly conveys the intent of your code. Related: New Features in C# 6.0 | C# Challenge - Predict the OutputComments |