Skip to content

Instantly share code, notes, and snippets.

@ferventcoder
Created August 2, 2011 16:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferventcoder/1120638 to your computer and use it in GitHub Desktop.
Save ferventcoder/1120638 to your computer and use it in GitHub Desktop.
IEnumerable Null Safeguard Extension - Useful When Iterating (ForEach Loop)
foreach (var item in items ?? new List<string>())
{
//do something
}
public static class EnumerableExtensions
{
public static IEnumerable<T> OrEmptyListIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
}
foreach(var item in items.OrEmptyListIfNull())
{
//do something
}
@ferventcoder
Copy link
Author

Saves about two lines of code to check for null and do something else since the foreach loop does no such thing for you.

Original question posed: http://twitter.com/ferventcoder/status/98435754883166208
"Wow...is this a clever hack or good safeguarding? https://gist.github.com/1120638"

@stevehorn
Copy link

If there is uncertainty about the code returning 'items' (web service/3rd party), I say great!

If you control how 'items' comes into your method, I'd say just go back and make sure that it always returns an empty list, and not null.

@chrisortman
Copy link

I think I prefer

items.ForEach(x => {

});

or

foreach(var item in items.EnsureNotNull()) {

}

Don't really have good justification, just my sensibilities

@ferventcoder
Copy link
Author

I never trust anything coming into my method... due to future maintenance. Should the method trust what comes in even if it is part of an encapsulated private method? I usually don't. :D

So the question really comes down to whether I should do that or one of the following items:

if (items !=null) {
 //foreach above
}

or

if (items == null) return;

@ferventcoder
Copy link
Author

Ooh.... the foreach extension.... :D
Thanks @chrisortman !

@stevehorn
Copy link

This book is great for these types of questions:
http://is.gd/TYQUYA

@ferventcoder
Copy link
Author

Suggested by cammerman https://gist.github.com/1120655

http://twitter.com/cammerman/status/98438025121505280
"@ferventcoder My implementation is a little more generalized: http://is.gd/1LpCSW"

@ferventcoder
Copy link
Author

http://twitter.com/sclarson/status/98436532796534784
"@ferventcoder for how many times I have been assigned tickets that require fixing the problem that safeguards I'm going to go with good."

@ferventcoder
Copy link
Author

Think I like @cammerman's the best... most elegant... and reusable... multiple wins! Close second is Chris Ortman. Didn't see the code though. ;)

@davidalpert
Copy link

I agree with @chrisortman.

I much prefer linqish extension methods over the foreach block as it wraps up ceremony in a more declarative syntax.

Though AFAIK the following code

items.ForEach(x => {...});

will throw a NullReference exception if items is null, so you'd be safer to write:

(items ?? Enumerable.Empty<string>()).ForEach(x => {...});

or, as @stevehorn suggested,

items = items ?? Enumerable.Empty<string>());
items.ForEach(x => {...});

or even, to hide this ceremony further, wrap .ForEach(...) in your own extension method

public static void Each<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null)
         return;
    source.ForEach(x => action(x));
 }

I've also seen similar useful overloads like

public static void Each<T>(this IEnumerable<T> source, Action<T, int> action)
{
    if (source == null)
         return;

    int i = 0;
    foreach(T item in source) {
        action(item, i++);
    }
 }

Come to think of it, are you sure that foreach will throw if the source is null? I know if the source is empty it simply short-circuts....

@jglozano
Copy link

jglozano commented Aug 2, 2011

I typically do all this as an assignment outside the looping construct - extensions are nice but they can be confusing.

items = items ?? new List();

or

var list = items ?? new List();

is cleaner IMO

@ferventcoder
Copy link
Author

@jglozano: I started down that path and thought, I could shortcut this at the point of the loop...

@ferventcoder
Copy link
Author

Late entry by @damianh (randompunter on twitter) - https://gist.github.com/1120821

http://twitter.com/randompunter/status/98457825998684160

"@ferventcoder in a similar vein https://gist.github.com/1120821"

Good stuff. The name of the extension is a little more clear.

@ferventcoder
Copy link
Author

I settled on the extension method named OrEmptyListIfNull. This directly borrows from @cammerman's https://gist.github.com/1120655 ;)

as in

foreach(var item in items.OrEmptyListIfNull()) 
{
  //do something
}

I posted the code back at the top of this gist.

@ferventcoder
Copy link
Author

This feels like community design... :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment