Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

I Wish C# Didn't Throw When Iterating Over Null Collections

DZone's Guide to

I Wish C# Didn't Throw When Iterating Over Null Collections

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.

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 :)


Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

Topics:

Published at DZone with permission of Toni Petrina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}