The last couple of weeks I have been playing around with ruby and ruby on rails. I really like the natural flow of the syntax in the language and got inspired to bring parts of that to C#.
In ruby you can write iterations like this:
4.times do
print "Yo!"
end
The above code snippet will execute "print "Yo!"" four times like a for statement. In addition to the simple times method there is also upto and step which will iterate to an upper bound and take other steps then +1. Have a look here http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html if you want to learn more about ruby expressions.
This syntax is really neat, I want it in my everyday coding?
In C# 3.0 we have the ability to extend types with "Extension Methods" technology. Since I liked this syntax so much I decided to extend Int to have similar functionality. My first attempt was to mimic the "times" syntax. The built in Func<> type requires a return type and since I just want to execute the code, not handle any result, I first needed a simple void() delegate:
public delegate void Func();
The extension method was then simple to implement:
public static void Times(this int ubound, Func codeBlockToExecute) {
for ( int index = 0; index < ubound; index ++) {
codeBlockToExecute.Invoke();
}
}
(If you are unfamiliar to extension methods, this is good reading: http://www.interact-sw.co.uk/iangblog/2005/09/26/extensionmethods )
Now armed with this method we can utilize that the C# compiler handles numbers in text as integers by default and use our Times function:
5.Times(delegate {
Console.WriteLine("Yo!");
});
Not as beautiful as the original, the delegate keyword kind of takes away the grace a bit, but still functional enough. Using lambda it is possible to make it a bit more slick but not as flexible since lambda in C# only supports the execution of a single line of code, but still have a look at this:
5.Times( () => Console.WriteLine("Yo !"));
Attached to this post (you need to go to the website to get it) is the code for this and other ruby like extensions including the "step" and "upto" ones. The code is written and compiled on the Orcas march CTP.
Playing around with this and some other extension a bit I got a wish list for the C# team:
- Func delegate with no return parameters (I know, I am lazy)
- Extension Properties ( 5.Times.Do() would really be cool to do)
- Handle {1,2,3} alone on a line as an array, so we could do {1,2,3}.foreach.do()
I guess I will pester the team about it when I get to Redmond in a couple of weeks.