BuddyJoe
BuddyJoe

Reputation: 71101

List.ForEach method and collection interfaces

In .NET 3.5 List<> gains a ForEach method. I notice this does not exist on IList<> or IEnumerable<> what was the thinking here? Is there another way to do this? Nice and simple short way to do this?

I ask because I was at a talk where the speaker said always use the more general interfaces. But why would I use IList<> as a return type if I want to be able to turn around and use ForEach? Then I would just end up casting it back to a List<>.

Upvotes: 3

Views: 333

Answers (3)

Why is ForEach not in IEnumerable<T>? Eric Lippert explains this nicely in his blog. Basically, LINQ is meant to be functional (no side effects), and ForEach is decidedly non-functional.

But, why is it not in IList<T>? Well... it should be!

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838156

what was the thinking here?

You can read Eric Lippert's blog for the reasons why this feature wasn't added.

Is there another way to do this? Nice and simple short way to do this?

Why not just use the foreach keyword? I find it more readable.

foreach (var foo in ilist)
{
    // etc...
}

Though you can add a ForEach extension method to IEnumerable<T> if you want to:

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (T item in enumeration)
    {
        action(item);
    }
}

Taken from here.

Upvotes: 4

Peter Oehlert
Peter Oehlert

Reputation: 16938

It's not in the framework (yet) but Rx adds the .Run(this IEnumerable enumerable) extension method that does the same as List's custom ForEach. Until this is part of the standard framework you'll have to write your own or use the extra dependency.

Upvotes: 1

Related Questions