Found another inter­est­ing post on Eric Lippert’s blog, this one explain the ratio­nales behind why there’s no built-in Enumerable.ForEach exten­sion method, one which myself and no doubt many oth­ers had decided to imple­ment ourselves.

As he explains, there are two main philo­soph­i­cal rea­sons why he’s against such an exten­sion method:

“The first rea­son is that doing so vio­lates the func­tional pro­gram­ming prin­ci­ples that all the other sequence oper­a­tors are based upon. Clearly the sole pur­pose of a call to this method is to cause side effects.

“The sec­ond rea­son is that doing so adds zero new rep­re­sen­ta­tional power to the lan­guage. Doing this lets you rewrite this per­fectly clear code:

foreach(Foo foo in foos){ state­ment involv­ing foo; }

into this code:

foos.ForEach((Foo foo)=>{ state­ment involv­ing foo; });

which uses almost exactly the same char­ac­ters in slightly dif­fer­ent order. And yet the sec­ond ver­sion is harder to under­stand, harder to debug, and intro­duces clo­sure seman­tics, thereby poten­tially chang­ing object life­times in sub­tle ways.”

Well, that clears a few things up, hear­ing from one of the guys on the C# com­piler team.

Ref­er­ences:

Eric Lip­pert – fore­ach vs ForEach

Share

Leave a Reply