I often come across code like the following:
if ( items != null)
{
foreach(T item in items)
{
//...
}
}
Basically, the
the second will throw a NullReferenceException
with the message Object reference not set to an instance of an object.
Actually there is a feature request on that @Connect: http://connect.microsoft.com/VisualStudio/feedback/details/93497/foreach-should-check-for-null
And the response is quite logical:
I think that most foreach loops are written with the intent of iterating a non-null collection. If you try iterating through null you should get your exception, so that you can fix your code.
You do need this. You'll get an exception when foreach
accesses the container to set up the iteration otherwise.
Under the covers, foreach
uses an interface implemented on the collection class to perform the iteration. The generic equivalent interface is here.
The foreach statement of the C# language (for each in Visual Basic) hides the complexity of the enumerators. Therefore, using foreach is recommended instead of directly manipulating the enumerator.
You could always test it out with a null list... but this is what I found on the msdn website
foreach-statement:
foreach ( type identifier in expression ) embedded-statement
If expression has the value null, a System.NullReferenceException is thrown.
The test is necessary, because if the collection is null, foreach will throw a NullReferenceException. It's actually quite simple to try it out.
List<string> items = null;
foreach(var item in items)
{
Console.WriteLine(item);
}
You still need to check if (items != null) otherwise you will get NullReferenceException. However you can do something like this:
List<string> items = null;
foreach (var item in items ?? new List<string>())
{
item.Dump();
}
but you might check performance of it. So I still prefer having if (items != null) first.
Based on Eric's Lippert suggestion I changed code to:
List<string> items = null;
foreach (var item in items ?? Enumerable.Empty<string>())
{
item.Dump();
}