squares.Each(val => Console.WriteLine(val));
Why not just do
foreach (var val in squares) Console.WriteLine(val);
Pretty simple, faster, and no funky extension methods to worry about (+ you dont have to write another using *** at the top of every class file). Guess its not as cool though ;)
Also, not to nitpick, but:
"""Each() method is basically a Visitor pattern implementation. """
Thinking about "Each" as any kind of pattern waaaaay over complicates it. Its just iteration over elements. :)
Thanks guys for mentioning Action delegate, I'm confirmed total ignoramus. I updated the code.
Scott, I think I have to declare generic parameter in method declaration - first AFAIK there is no non-generic Action version and then it would require working with object and so downcasting in lambda function. I'm not sure I'm following you though.
Btw, I omitted generic parameter in usage code - it could be written as
but I wanted to be it as close to Ruby as it can be.
Mark, IndexedAction is also good idea, that matches Ruby's Enumerable.each_with_index() method.
(woking in .Neet 2.0)
The List class has a ForEach function :-
public void ForEach(Action action)
, which is not as flexible as your extension methods, but you may wish to utilise the Action delegate from the System namespace:-
public delegate void Action(T obj);
Having said that I then created another delegate:-
public delegate bool IndexedAction(T item, int position);
to pass the index and the object.
 Rather than define a new delegate why not simply use the existing Action?
 Surely you have to declare your generic parameter?
public static void Each(this IEnumerable source, Action sub), and
public static void EachIndex(this IEnumerable source, Action sub)
Nit-picking aside; that is a slick solution. :-)