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)
{
...