Skip to content

Instantly share code, notes, and snippets.

@damianh
Created August 2, 2011 18:16
Show Gist options
  • Save damianh/1120821 to your computer and use it in GitHub Desktop.
Save damianh/1120821 to your computer and use it in GitHub Desktop.
IEnumerable ForEach safety extensions
namespace System.Collections.Generic
{
using System.Linq;
public static class IEnumerableExtensions
{
// Why ForEach extension is not included on IEnumerable<T> by default http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
Guard.Against(action == null, new ArgumentNullException("action"));
if(source == null) return;
foreach (T t in source)
{
action(t);
}
}
public static void ForEachSkipNull<T>(this IEnumerable<T> source, Action<T> action)
{
Guard.Against(action == null, new ArgumentNullException("action"));
if(source == null) return;
foreach (T t in source.Where(t => !ReferenceEquals(t, null)))
{
action(t);
}
}
public static void ForEachThrowOnNull<T>(this IEnumerable<T> source, Action<T> action)
{
Guard.Against(action == null, new ArgumentNullException("action"));
if(source == null) return;
foreach (T t in source)
{
if (ReferenceEquals(t, null))
{
throw new InvalidOperationException("Item is null");
}
action(t);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment