Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading