1

Let's assume I have a method:

private ObservableCollectionExtended<Record> myCollection;

public void SetLoadingProperty(bool isLoading)
{
  if (!myCollection?.Any() ?? false)
    return;

  foreach(var record in myCollection)
  {
    record.IsLoading = isLoading;
  }
}

Is there any circumstance under which I get NullReferenceException for myCollection being null in the foreach loop?

krs
  • 543
  • 2
  • 17
  • 3
    `if (!myCollection?.Any() ?? false)` won't be evaluated to `true` if the collection is null. that's equivalent to `if ((!myCollection?.Any()) ?? false)` – Cid Mar 28 '22 at 09:18

2 Answers2

4

You only need a null check in your method:

private ObservableCollectionExtended<Record> myCollection;

public void SetLoadingProperty(bool isLoading)
{
  if (myCollection == null)
    return;

  foreach(var record in myCollection)
  {
    record.IsLoading = isLoading;
  }
}

If your collection doesn't contain any items, the loop just won't be executed. The check for Any is not necessary. Always try to write as simple code as possible.

Online demo: https://dotnetfiddle.net/ComNsN

SomeBody
  • 7,515
  • 2
  • 17
  • 33
  • 1
    I would advise to go with the `is` operator instead of `==` here since it avoids problems when overloading the `==` operator. [for reference](https://stackoverflow.com/a/40676671/7935403) – J. Bergmann Mar 28 '22 at 09:36
  • 1
    @J.Bergmann [Class `ObservableCollectionExtended<>`](https://www.reactiveui.net/api/dynamicdata.binding/observablecollectionextended_1/) does not seem to overload the `operator ==`. To me, `== null` is fine, but it is only a matter of style. In the unlikely situation an overload of `operator ==` is introduced one day, the damage is not too bad because that operator will surely return the right thing when arguments are `null`. If you are really paranoid, you can use `is`, or you can cast either side to `object`, as in `(object)myCollection == null` or `myCollection == (object)null`. – Jeppe Stig Nielsen Mar 28 '22 at 09:49
1

Did you mean:

  if (!(myCollection?.Any() ?? false))
    return;
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181