Adventures in .NET 3.5 Part 2 - Ruby Blocks

In my previous post, I talked about .NET 3.5 Extension Methods and ended by mentioning Ruby Blocks - because they are much admired.  As one example in Ruby, one might output the sum of an array of numbers as follows ...

      list = [1,2,3,4,5,6,7,8,9,10]
      sum = 0
      list.each() {|i| sum = sum + i}
      puts sum

What is now possible in .NET 3.5?  Well, one could write the following C# code ...

      int[] list = {1,2,3,4,5,6,7,8,9,10};
      var sum = 0;
      list.Each(i => sum += i);
      sum.Print();      // an extension method from my previous post

How is the "Each" method above implemented?  As an Extension method as follows ...

      public static void Each<T>(this IEnumerable<T> items, Action<T> action) {
          foreach (var item in items)

One could use this Extension Method to apply any statement against each item in a collection.  For example, I could now output each item to the console with the following statement ...

      list.Each(i => i.Print());

For me, this is a slightly better syntax in this circumstance than the built in Array.ForEach<T> method which also takes an Action<T> as a parameter.
In other words, I prefer writing list.Each(i => sum += i); instead of  Array.ForEach(sports, i => sum += i);

1 Comment

Comments have been disabled for this content.