Skip to content

Instantly share code, notes, and snippets.

@robgough
Last active December 16, 2015 15:49
Show Gist options
  • Save robgough/5458307 to your computer and use it in GitHub Desktop.
Save robgough/5458307 to your computer and use it in GitHub Desktop.
Borrows the "3.times" style syntax from Ruby and puts it in C# with an extension method
public class MyClass
{
public void MyMethod(int repeat)
{
repeat.Times(i => {
Console.WriteLine(String.Format("Repeat {0}", i));
}, 1);
}
}
/*
MyMethod(5) =>
Repeat 1
Repeat 2
Repeat 3
Repeat 4
Repeat 5
*/
public static class IntegerExtensions
{
public static void Times(this int value, Action<int> action, int offset = 0)
{
for (int i = offset; i < value + offset; i++)
{
action(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment