Last active
December 16, 2015 15:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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