0

I just started learning LINQ and then just stuck on an example statement provided in the tutorial (Please not that I am working with C# .Net Framework). The statement

 arr?.Count(w => w != null) > 0

returns True only if their is at-least one none-null element in the arr (array or list). But what is the ? operator doing there? Is this another form or ternary operator or something else? Please share your precious knowledge on this point. I shall be glad and thankful to read good answers from you.

Note: I tried removing the ? operator in the statement but could not find any difference.

HN Learner
  • 544
  • 7
  • 19

1 Answers1

2

It's the Null conditional operator

It's basically checking for null and executing the condition if not null. In the case arr was null, this code would not throw an exception. If written without the Null Conditional operator you would get a NullReferenceException.

// this would throw an exception
int?[] arr;
arr.Count(w => w != null) > 0;

// this will check if arr is null and not proceed to call the .Count method
int?[] arr;
arr?.Count(w => w != null) > 0;
Dan D
  • 2,493
  • 15
  • 23