krs
krs

Reputation: 599

Possible NullReferenceException - but why?

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?

Upvotes: 1

Views: 109

Answers (2)

SomeBody
SomeBody

Reputation: 8743

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

Upvotes: 4

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Did you mean:

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

Upvotes: 1

Related Questions