.NET Zone is brought to you in partnership with:

My name is Toni Petrina and I am a software developer and an occasional speaker. Although I primarily develop on the Microsoft stack, I like to learn new technologies. My hobbyist projects range from game development, regardless of the technology, to ALM. I spend most of my time with my girlfriend and someday I will learn how to play the guitar properly. Toni is a DZone MVB and is not an employee of DZone and has posted 69 posts at DZone. You can read more from them at their website. View Full User Profile

I Wish That C# Didn’t Throw When Iterating Over a Null Collection

12.08.2012
| 1779 views |
  • submit to reddit

Consider the following code:

List<string> list = null;
foreach (var element in list)
  //... NullReferenceException above

Boom, in your face! We want to go through all elements in the nonexisting collection. Not empty, but nonexisting. While you may argue that semantically there is some difference, when do you actually want that exception to blow up? Fix is easy, but ugly:

if (list != null)
{
    foreach (var element in list)
        //
}

One way to implement this would be to allow a compiler flag that will expand foreach (var element in list) into:

if (list != null)
    foreach (var element in list)

This is the same question as before: should you ever return null collections.

My answer is no, forget the null and make code prettier :)

Published at DZone with permission of Toni Petrina, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)