Search code examples
c#nullreferenceexceptionnull-coalescing-operator

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?


Solution

  • 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