foreach null

  • Thread starter Thread starter Peter Kirk
  • Start date Start date
P

Peter Kirk

Hi

if I have a foreach loop over a list, do I get a NullReferenceException if
one of the objects in the list is null?

For example, say I have a list "persons" of IPerson objects, but one of the
objects in the list is actually null.

foreach (IPerson person in persons)
{
// do something with person...
}


Thanks,
Peter
 
null is a perfectly valid IPerson, so no, foreach won't break; however, it
will be returned (as null), and so /your/ code might blow up when it tries
to use it; as such, you may wish to simply exclude this from your
considerations:

foreach(IPerson person in persons) {
if(person == null) continue;
// do something with person
}

However, if persons is null, then I would expect bad things to happen.

Marc
 
Marc Gravell said:
null is a perfectly valid IPerson, so no, foreach won't break; however, it
will be returned (as null), and so /your/ code might blow up when it tries
to use it; as such, you may wish to simply exclude this from your
considerations:

foreach(IPerson person in persons) {
if(person == null) continue;
// do something with person
}

However, if persons is null, then I would expect bad things to happen.

Yes, thanks. I found the exception I was getting was actually from the
list - which came from another containing object, and was null.

Peter
 
Mike Barakat said:

No. You end up with a null reference as the value of the variable
involved in the loop. Here's an example:

using System;
using System.Collections;

class Test
{
static void Main()
{
ArrayList list = new ArrayList();
list.Add("Before null");
list.Add(null);
list.Add("After null");

foreach (string x in list)
{
Console.WriteLine ("Is the value null? {0}", x==null);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top