Null-conditional Operators in C#
Posted On: 15-May-2016 03:40
"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.
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.
int? length = Players?.Length; // null if Players is null
Players first = Players?; // null if Players is null
int? count = Players??.Batters?.Count(); // null if Players, the first Players, or Batters is null
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.
In the above article we see how the Null-conditional Operator will be helpful for checking the null. I hope it will help you.