Eric Lippert on the decision to omit Enumerable.ForEach

Found anoth­er 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 decid­ed to imple­ment our­selves.

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­tion­al pro­gram­ming prin­ci­ples that all the oth­er sequence oper­a­tors are based upon. Clear­ly 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­tion­al pow­er to the lan­guage. Doing this lets you rewrite this per­fect­ly 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 exact­ly the same char­ac­ters in slight­ly dif­fer­ent order. And yet the sec­ond ver­sion is hard­er to under­stand, hard­er to debug, and intro­duces clo­sure seman­tics, there­by poten­tial­ly 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­pil­er team.


Eric Lip­pert – fore­ach vs ForE­ach