Mobile 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 C# Didn't Throw When Iterating Over Null Collections

12.01.2012
| 5001 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.)

Comments

Tracy Sells replied on Mon, 2012/12/03 - 1:07am

If you aren't sure if the collection is null you should always check.  When iterating over a collection you are calling a method on the collection (GetEnumerator()).  This is just like trying to call the method BAR() on the object FOO when FOO doesn't exist - it is going to blow up.  Forget about pretty code for a second - if you are writing production software with at least one user - you better make sure that foreach loop NEVER blows up due to a null variable.  

Naiden Gochev replied on Mon, 2012/12/03 - 3:03am

Hi Toni Petrina, this is the same with ALL languages this is nothing only specific for C# and the forach. The Foreach on all languages works like that if the collection is null NPE... in Java it is the same :) so make your != null before that or make sure to prepare your domain objects to always have for example empty collection assigned or something like that also make sure the ORM framework have configuration and is configured to return empty instead of null collections in case of 0 records. This will help you to not write this ugly != but I believe they are quite nice :P 

Toni Petrina replied on Mon, 2012/12/03 - 4:05am in response to: Tracy Sells

Hi Tracy,

Yes, I am well aware of the current semantics, this is simply my wish :)

Since foreach is just a syntactic sugar that expands into some code similar to this:

using (var enumerator = collection.GetEnumerator())
    while (enumerator.MoveNext())
         DoCode with enumerator.Current...

I would love it if the default "expansion" is similar to this:
if (collection != null)
  using (var enumerator = collection.GetEnumerator())
   while (enumerator.MoveNext())
    DoCode with enumerator.Current...

Like I said, this is only my wish :)

Toni Petrina replied on Mon, 2012/12/03 - 4:10am in response to: Naiden Gochev

Hi Naiden,

I argue that you rarely need to make distinction between an empty collection and a null collection. That is why I would like to enforce globally that that distinction is ignored by compiler too.

This way compiler could do the job instead.

Naiden Gochev replied on Mon, 2012/12/03 - 4:53am

Toni I believe the compiler is already doing a lot of things like the Nullable<type> and the new async await wrapping unwrappnig.

I agree usually you don't need different handling for a empty and null collection however I guess it will be different unexpected behavior for the other languages. I mean if this is "done" it probably should be done for all .net languages not just C# otherwise will be a bit weird and unexpected 

Krzysztof Wilk replied on Mon, 2012/12/03 - 5:28am in response to: Naiden Gochev

this is the same with ALL languages this is nothing only specific for C# and the forach

It's not true. In Groovy, for example, this executes without NPE:

List list = null
for (element in list)
  println element

Naiden Gochev replied on Mon, 2012/12/03 - 5:45am

Krzysztof well ok groovy have made a hack in the groovyc still I am sure that 99.9% of the groovy devs still check for != null before that :) even if it is not required.

Krzysztof Wilk replied on Mon, 2012/12/03 - 6:27am in response to: Naiden Gochev

 I'm sure that huge part of Groovy developers have chosen Groovy not Java (or any other language) because of its enhancements in, for example, handling nulls. I am just starting to learn C# but already miss groovy's safe navigation feature (var?.field or var?.method()), especially in ASP.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.