简体   繁体   中英

IEnumerable not null, but throwing a NullReferenceException on iteration

I have an IEnumerable that I run a foreach on. It's throwing a null reference exception in certain cases on the foreach line, it says

ienumerable threw an exception of type 'System.NullReferenceException

if (ienumerable != null)
{
    foreach (var item in ienumerable)
    {
        ......
    }
}

I put in a null check before the foreach loop, and the iEnumerable passes the null check, but then when I run the foreach loop on it it throws the null reference exception.

Iterators can do just about anything when iterated, including throw exceptions. So basically, you need to know what the source is. For example, this is a non-null iterator that throw in the same way:

var customers = new [] {
    new Customer { Name = "abc" },
    new Customer { },
    new Customer { Name = "def" }
};
IEnumerable<int> lengths = customers.Select(x => x.Name.Length);

this won't fail until the second time through the loop. So: look at where the iterator came from, and how the iterator is implemented.

Purely for fun, here's another that will fail identically:

IEnumerable<int> GetLengths() {
    yield return 3;
    throw new NullReferenceException();
}

the items in your ienumerable are sometimes null,

try this:

    if (ienumerable != null)
    {
        foreach (var item in ienumerable)
        {
            if(item != null)
            {
               // do stuff
            }

        }
    }

here is an example to try for you guys.

        string[] testStr = new string[] { null, "", "test" };
        foreach (var item in testStr)
        {
            if (item != null)
            {
                Console.WriteLine(item);
            }
            else
            {
                Console.WriteLine("item was null");
            }
        }

        Console.ReadKey();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM