Null-conditional Operators in C#

Views: 2099
Comments: 0
Like/Unlike: 0
Posted On: 15-May-2016 03:40 

Share:   fb twitter linkedin
NiceOne...
Editor
1382 Points
14 Posts

Introduction

"Object Reference not set to an instance of an Object" is a run time error message. It is a common error message that every C# programmer will be familiar with it. The main cause of this error message is performing some operation on null object. In Previous version we can prevent this error through if condition by checking null. But Now in .Net 6.0 we have Null-conditional Operators. 

Uses

Null-conditional Operator (?) 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.

Examples

int? length = Players?.Length; // null if Players is null
Players first = Players?[0]; // null if Players is null
int? count = Players?[0]?.Batters?.Count(); // null if Players, the first Players, or Batters is null

Explanation

 The last example shows 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. 

Conclusion

 In the above article we see how the Null-conditional Operator will be helpful for checking the null. I hope it will help you.

0 Comments
 Log In to Chat