6

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.

Erica Stockwell-Alpert
  • 4,624
  • 10
  • 63
  • 130
  • 3
    You haven't provided us enough information. How is your `ienumerable` populated? –  Oct 12 '16 at 19:44
  • 2
    Please show how you get this IEnumerable. If you used linq like the tags suggest it could be that somewhere there you get the null reference but being differed executed you will see it only when actually executing – Gilad Green Oct 12 '16 at 19:45
  • `IEnumerable`s are evaluated as you iterate them. Where is the `IEnumerable` getting its items from? – Brandon Oct 12 '16 at 19:45
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – hatchet - done with SOverflow Oct 12 '16 at 19:47
  • The other question: Is it the loop itself (the `foreach`) or the work in the loop that uses `item`? – Brandon Oct 12 '16 at 19:48
  • @Fabio - if he gets the exception on the line of the foreach then it is not because the item is null -> but because something is null when trying to achieve that item – Gilad Green Oct 12 '16 at 19:48
  • IMO the exception is being thrown from an iterator function. –  Oct 12 '16 at 19:48
  • It's pretty hard to answer your question without seeing how you assign `ienumerable`. That's where you should be looking. – hatchet - done with SOverflow Oct 12 '16 at 19:50

2 Answers2

5

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();
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

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();
C Smith
  • 222
  • 1
  • 6
  • Or `item.item.item != null` – H H Oct 12 '16 at 19:50
  • This would not result in the behavior described of the `IEnumerable` erroring when fetching the next item. – Servy Oct 12 '16 at 19:52
  • @Servy it would if the IEnumerable was created with a .Where() or similar and the where throws the error (this answer identifies that problem but its solution won't fix the issue.) – Scott Chamberlain Oct 12 '16 at 19:56
  • Yes you are correct, an enumerable such as a list can be not null but still have a count of 0. And each item in the Enumerable does not have a null check against its properties in the code listed above. More detail will reveal the truth... – Mr.Bigglesworth Oct 12 '16 at 19:58
  • 1
    @ScottChamberlain That an item in an `IEnumerable` is `null` doesn't result in an exception when iterating through it. If the `IEnumerable` throws an exception when trying to generate an item then there *is* not corresponding item in the sequence at that position; the sequence is errored. There are an infinite number of possible ways for a sequence to error when generating an item, but none of them is that "that item in the sequence is `null`". This answer is very specifically referring to the iterator *successfully yielding a null value*, which is very clearly not the OP's situation. – Servy Oct 12 '16 at 19:59