Null-conditional Operators (C# and Visual Basic)
Updated: July 20, 2015
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
Used to test for null before performing a member access (
?.) or index (
?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.
int? length = customers?.Length; // null if customers is null Customer first = customers?; // null if customers is null int? count = customers??.Orders?.Count(); // null if customers, the first customer, or Orders is null
The last example demonstrates that the null-condition operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops. Other operations with lower precedence in the expression continue. For example,
E in the following always executes, and the
== operations execute.
Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following:
The new way is much simpler:
The new way is thread-safe because the compiler generates code to evaluate
PropertyChanged one time only, keeping the result in temporary variable.
You need to explicitly call the
Invoke method because there is no null-conditional delegate invocation syntax
PropertyChanged?(e). There were too many ambiguous parsing situations to allow it.
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.
For more information, see the Visual Basic Language Reference.