How to handle NullReferenceException in a foreach?

raz3r picture raz3r · Dec 20, 2010 · Viewed 14.6k times · Source
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!

Answer

Gabe picture Gabe · Dec 20, 2010

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.