Reputation: 3131
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
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
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
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