raz3r
raz3r

Reputation: 3131

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!

Upvotes: 8

Views: 18867

Answers (3)

TalentTuner
TalentTuner

Reputation: 17556

if it is the myField.getChilds() which may contain null

than

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

}

this way ,you can handel null or empty strings.

Upvotes: 2

Gabe
Gabe

Reputation: 86838

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.

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

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>())
{

}

Upvotes: 3

Related Questions