August 2010 Blog Posts

Giving C# a Times method

Want to be able to write code like “5.Times” but you can’t use a language like Ruby? You can do this in C# with some extension method magic. public static void Times(this int numberOfTimes, Action action) { for (var number = 0; number < numberOfTimes; number++) { action(); } } Now you can write code like: 5.Times(() => Console.WriteLine("Hello")); Sometimes however you want to know the index of the invocation of the lambda. This can be done with: public static void Times(this int numberOfTimes, Action<int> action) { ...

posted @ Saturday, August 14, 2010 1:36 PM | Feedback (0)