Ruby Inspired Sugary Syntactical Goodness for C#

I have been playing with Ruby recently and it has lead me to want a couple of methods off of commonly used objects. I have found myself typing each and times into my VS editor regularly rather than curse my primary language, I decided that I should just implement the the missing functions. It is surprisingly easy to do. Here are some snippets for you to drop into a static class:

//Each & Times
public static void Each<T>(this IEnumerable<T> enumerable, Action<T> block)
{
foreach (T item in enumerable)
{
block.Invoke(item);
}
}

public static void Times(this int count, Action block)
{
for (int i = 0; i < count; i++)
{
block.Invoke();
}
}

public static void Times(this int count, Action<int> block)
{
for (int i = 0; i < count; i++)
{
block.Invoke(i);
}
}

The usage should be fairly straightforward, but just in case you need a pointer, here is some code I took from one of my Bowling Game Kata practice sessions:

21.Times(() => _game.Roll(0));
...
private void MultipleRolls(params int[] rolls)
{
rolls.Each(x => _game.Roll(x));
}
...
5.Times(x => Console.Out.WriteLine("x = {0}", x));

Ok, so I faked the last one, but I think you get the picture. Let me know if you think this is useful and please post any similar tips that you use in your code.

UPDATE: I found some issues with the Each method. It works just find if you are using a concrete Enumerable. If you are using an Enumerable that is evaluated lazily like the results of Select, you will find that it cannot modify the content of your list because each time you enumerate, you will get new objects. I tried several options to resolve this, and they mostly turned the Each back into a Select, so I'm not sure about a clean solution for this one. If you call ToList() on your Enumberable before you call each, you might as well just use the ForEach() method on List(). Still pondering if there is value. Every solution I think of reduces the clarity of the code.

Comments

  1. I found the syntax highlighter here:
    http://www.craftyfella.com/2010/01/syntax-highlighting-with-blogger-engine.html

    Two things I noticed while using it:
    1. You need to html encode > & < or it will add tags to compensate.
    2. Don't use a really long first line or the credit tag will over write your code (hence the comment)

    ReplyDelete

Post a Comment

Popular posts from this blog

TFS to SVN Conversion with History

TDD vs BDD

System Architecture: Bounded Contexts