web analytics
null-conditional operator Options
codeling
Posted: Saturday, April 15, 2017 9:11:13 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 770
Points: 3234

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?[0];  // null if customers is null  
int? count = customers?[0]?.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.

Sponsor
Posted: Saturday, April 15, 2017 9:11:13 PM
 
codeling
Posted: Saturday, April 15, 2017 9:15:27 PM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 770
Points: 3234

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:

var handler = this.PropertyChanged;
if (handler != null)
    handler(…)

The new way is much simpler:

PropertyChanged?.Invoke(e)  

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.

Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.