Ruby-style iterations in C# 3.0
While Ruby does have a for-loop, it is not commonly used in idiomatic Ruby code. Instead, to loop a number of times and do something in each run you would write code like this:
5.times do |i| print i end # equivalent for loop over a range for int i in 0...5 print i end
I do not know about you, but I definitely like the 5.times way better. With the new C# 3.0 (as part of Linq) feature extension methods it is a trivial thing to make it possible to write very similar code in C#:
// using a lambda function, also a C# 3.0 feature
5.Times( i => Console.WriteLine(i) );
// or using a "simple" C# 2.0 delegate
5.Times(delegate (int i)
{
Console.WriteLine(i);
});
So how does this work? By creating an extension method for int and bringing that into scope (with a using statement) all ints will now be extended with the method Times. Actually, int has of course not really been modified “on the fly” to include a new method, it is really only syntactic sugar for a method call such as IntExtensions.Times(5, i => Console.WriteLine(i));. Here is the simple extension method:
public static class IntExtensions
{
public static void Times(this int count, Action<int> block)
{
for (int i = 0; i < count; i++)
{
block.Invoke(i);
}
}
}
So what do you think? Am I crazy for even thinking about writing my C# (3.0) code in this way? Would you get confused and angry by looking at the code?
Trackbacks
Trackbacks are closed.

