Created
August 2, 2011 16:50
-
-
Save ferventcoder/1120638 to your computer and use it in GitHub Desktop.
IEnumerable Null Safeguard Extension - Useful When Iterating (ForEach Loop)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
foreach (var item in items ?? new List<string>()) | |
{ | |
//do something | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
@jglozano: I started down that path and thought, I could shortcut this at the point of the loop...
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.
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.
This feels like community design... :D
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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