0

Possible Duplicate:
Why does .NET foreach loop throw NullRefException when collection is null?

foreach iterator throws the exception if the target collection is null.

Example:

List<string> names = null;
foreach(var name in names) { /* throws exception */ }

What is the design idea behind it. Isn't it handy to not iterate through the loop instead .NET Framework throwing exception?

Community
  • 1
  • 1
StartingFromScratch
  • 628
  • 3
  • 10
  • 23

2 Answers2

2

Generally, a null collection indicates that a collection is not valid. I would expect an empty collection to not iterate, but a null collection to exception as I was expecting a valid collection.

Why does .NET foreach loop throw NullRefException when collection is null?

Community
  • 1
  • 1
Ben
  • 539
  • 3
  • 7
0

I think that there is no idea behind. As you know foreach was added much later then Enumerator and foreach is built on it(*).

(*) foreach is somewhat equivalent to:

var enumerator = someList.GetEnumerator();
while (enumerator.MoveNext())
{
    //do something with enumerator.Current
}

You cannot run GetEnumerator on something which is null.

Andriy Buday
  • 1,959
  • 1
  • 17
  • 40
  • 1
    In which version of C# did you think `foreach` was introduced? – phoog Mar 23 '12 at 23:16
  • In version 2.0 you got possibility to write foreach for your own collections. – Andriy Buday Mar 23 '12 at 23:34
  • I just found this confirming this: http://www.wrox.com/WileyCDA/Section/What-s-New-in-the-NET-Framework-2-0.id-290323.html See: Iterators. – Andriy Buday Mar 23 '12 at 23:35
  • 3
    No, in version 1.0 you could write collections that could be used with foreach. The foreach statement is "duck typed"; the collection type must have a `GetEnumerator()` method and the type returned by the GetEnumerator method must have a `bool MoveNext()` method and a `Current` property. – phoog Mar 23 '12 at 23:36
  • You're welcome :) See this blog post from Eric Lippert for a discussion: http://blogs.msdn.com/b/ericlippert/archive/2011/06/30/following-the-pattern.aspx – phoog Mar 23 '12 at 23:39