Home > OS >  Possible NullReferenceException - but why?
Possible NullReferenceException - but why?

Time:03-29

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?

CodePudding user response:

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

CodePudding user response:

Did you mean:

  if (!(myCollection?.Any() ?? false))
    return;
  • Related