A statement using the conditional operator such as this
1
int
? age = p ==
null
?
null
: p.Age;
…can be simplified:
1
int
? age = p?.Age;
1
| int ? age = p == null ? null : p.Age; |
1
| int ? age = p?.Age; |
Together with the Coalescing Operator
In case the variable
firstName
shouldn’t be null but instead should contain an empty string, the null conditional operator works great in combination with the coalescing operator:
1
2
3
4
5
| public void ShowPerson(Person p) { string firstName = p?.FirstName ?? string .Empty; //... } |
int? length = people?.Length; // null if people is null
Person first = people?[0]; // null if people is null
Type personType = people?[0].GetType(); // null if people is null
int length = people?.Length ?? 0; // 0 if people is null
int? count = customers?[0].Orders?.Count();
if (myDelegate?.Invoke(args) ?? false) { … } // when null is returned, then false for if
The ?. Operator
Null 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;
========================
public void DoSomething(Order order)
{
string customerName = order?.Customer?.Name;
}
============================
How the new operator workS
Consider getting the grandchild of a parent object like this:
var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO
Wow! That’s the equivalent of testing every single level, but in a single line of code. The “?.” operator is basically saying, if the object to the left is not null, then fetch what is to the right, otherwise return null and halt the access chain.
It’s a wonderful addition to the language’s syntax.
No comments:
Post a Comment