Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle NullReferenceException in a foreach?

foreach (string s in myField.getChilds()) {
    if (s == null)
        //handle null
    else
        //handle normal value 
}

When I run my program i get a NullReferenceException because getChilds may return null. How can I make my program to continue anyway and handle the exception? I can't handle it outside of the foreach, can't explain why because it will take too much time (and I am sure you guys are busy :P). Any ideas?

I already tryed that way:

foreach (string s in myField.getChilds() ?? new ArrayList(1)) {
        if (s == null)
            //handle null
        else
            //handle normal value 
    }

But it does not work, program just jump at the end of the foreach but I want it to enter the foreach instead!

like image 571
raz3r Avatar asked Dec 20 '10 08:12

raz3r


People also ask

How do you handle NullReferenceException?

Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.

Can NullReferenceException be caught?

Find out which exception you're receiving, and either catch that specific exception, or else prevent it from occurring in the first place. You should never catch NullReferenceException.

What does system NullReferenceException mean?

A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.


2 Answers

One way to do this (though not the best way) is:

foreach (string s in myField.getChilds() ?? new string[] { null })

or

foreach (string s in myField.getChilds() ?? new ArrayList { null })

The reason new ArrayList(1) doesn't work is that it creates a list that has the capacity to hold 1 element, but is still empty. However new string[] { null } creates a string array with a single element which is just null, which is what you appear to want.

like image 179
Gabe Avatar answered Sep 30 '22 14:09

Gabe


var children = myField.getChilds();
if (children == null)
{
    // Handle the null case
}
else
{
    foreach (string s in children)
    {

    }
}

or simply use the null coalescing operator:

foreach (string s in myField.getChilds() ?? Enumerable.Empty<string>())
{

}
like image 38
Darin Dimitrov Avatar answered Sep 30 '22 14:09

Darin Dimitrov