Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no ForEach extension method on IEnumerable?

Inspired by another question asking about the missing Zip function:

Why is there no ForEach extension method on the IEnumerable interface? Or anywhere? The only class that gets a ForEach method is List<>. Is there a reason why it's missing, maybe performance?

like image 764
Cameron MacFarland Avatar asked Sep 19 '08 11:09

Cameron MacFarland


People also ask

Can I use foreach in IEnumerable C#?

The IEnumerator interface provides iteration over a collection-type object in a class. The IEnumerable interface permits enumeration by using a foreach loop.

How do you foreach in Linq?

Convert a foreach loop to LINQ refactoringPlace your cursor in the foreach keyword. Press Ctrl+. to trigger the Quick Actions and Refactorings menu. Select Convert to LINQ or Convert to Linq (call form).

What is IEnumerable interface in C#?

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.


1 Answers

There is already a foreach statement included in the language that does the job most of the time.

I'd hate to see the following:

list.ForEach( item => {     item.DoSomething(); } ); 

Instead of:

foreach(Item item in list) {      item.DoSomething(); } 

The latter is clearer and easier to read in most situations, although maybe a bit longer to type.

However, I must admit I changed my stance on that issue; a ForEach() extension method would indeed be useful in some situations.

Here are the major differences between the statement and the method:

  • Type checking: foreach is done at runtime, ForEach() is at compile time (Big Plus!)
  • The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething);
  • ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.

Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.

like image 122
Coincoin Avatar answered Oct 17 '22 22:10

Coincoin