Alex Hoffman

Perspective on development, management and technology

Syndication

News

    Subscribe

    IASA Member

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)
          {
              action(item);
          }
      }

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);

Published Saturday, August 04, 2007 7:11 PM by Alex Hoffman

Filed under: , ,

Comments

# Adventures in .NET 3.5 Part 3@ Monday, August 06, 2007 4:08 AM

This is the 3rd part in a series. See Part1 and Part 2 . Inferring a Collection Type In C# 3.5, the compiler

Alex Hoffman

# Adventures in .NET 3.5 Part 4@ Monday, August 06, 2007 9:47 PM

This is the 4th part in a series. See Part1 , Part 2 and Part3 . Extension Methods continued So, where

Alex Hoffman

# re: Adventures in .NET 3.5 Part 2 - Ruby Blocks@ Sunday, October 14, 2007 4:57 PM

list = list = [1,2,3,4,5,6,7,8,9,10]

puts list.inject(0) {|sum,i| sum+i}

Sam Ruby