16 October, 2007. It was a Tuesday.
I really love the readability and conciseness of this syntax, just enough to see what’s going on, but not a lot of extra stuff to get in the way. In addition to the “times” method, there’s also “upto” and “downto” methods for other looping scenarios.
With extension methods and lambda expressions and C# 3.0, this form of loop syntax is pretty easy to do. Not really a great idea, but at least an example of what these new constructs in C# 3.0 can do.
Now that the Times method shows up for ints, we can focus on the Do block.
Although I can’t declare blocks in C# 3.0, lambda expressions are roughly equivalent. To take advantage of lambda expressions, I want to give the behavior to the Times method in the form of a delegate. By declaring a delegate parameter type on a method, I’m able to use lambda expressions when calling that method.
Although the “for” syntax is functional and about the same number of lines of code, the Ruby version is definitely more readable. Adding additional UpTo and DownTo methods would be straightforward with additional ILoopIterator implementations.
Yeah, I know this is more than a mild case of feature abuse, but it was interesting to see the differences between similar operations in C# 3.0 and Ruby. Although it’s possible to do these similar operations, with similar names, this example highlights how much the syntax elements of the static CLR languages can get in the way of a readable API, and how much Ruby stays out of the way.