Page 200 - CSharp/C#
P. 200
// Handle async task
}
// If want to use information from the exception
if (ex != null)
{
await logger.LogAsync(e);
}
// Close the service, since this isn't possible in the finally
await service.CloseAsync();
Null propagation
The ?. operator and ?[...] operator are called the null-conditional operator. It is also sometimes
referred to by other names such as the safe navigation operator.
This is useful, because if the . (member accessor) operator is applied to an expression that
evaluates to null, the program will throw a NullReferenceException. If the developer instead uses
the ?. (null-conditional) operator, the expression will evaluate to null instead of throwing an
exception.
Note that if the ?. operator is used and the expression is non-null, ?. and . are equivalent.
Basics
var teacherName = classroom.GetTeacher().Name;
// throws NullReferenceException if GetTeacher() returns null
View Demo
If the classroom does not have a teacher, GetTeacher() may return null. When it is null and the Name
property is accessed, a NullReferenceException will be thrown.
If we modify this statement to use the ?. syntax, the result of the entire expression will be null:
var teacherName = classroom.GetTeacher()?.Name;
// teacherName is null if GetTeacher() returns null
View Demo
Subsequently, if classroom could also be null, we could also write this statement as:
var teacherName = classroom?.GetTeacher()?.Name;
// teacherName is null if GetTeacher() returns null OR classroom is null
View Demo
This is an example of short-circuiting: When any conditional access operation using the null-
https://riptutorial.com/ 146

