Here\'s a bit of code which prints out the squares of the numbers from 0 to 9:
for (int i = 0; i < 10; i++)
Console.WriteLine(i*i);
Doin
Turn it into an extension method (note the this before the n
parameter, which defines the type this method operates on):
static class MathUtil
{
public static void UpTo(this int n, Action proc)
{
for (int i = 0; i < n; i++)
proc(i);
}
}
Usage:
10.UpTo((i) => Console.WriteLine(i * i));
Note: The above method call isn't particularly intuitive though. Remember code is written once and read many times.
Maybe allowing something like below might be slightly better, but to be honest i'd still just write a foreach
loop.
0.UpTo(10 /*or 9 maybe*/, (i) => Console.WriteLine(i * i));
If you wanted this, then you could write an extension method like this:
public static void UpTo(this int start, int end, Action proc)
{
for (int i = start; i < end; i++)
proc(i);
}
Change <
to <=
if you want an inclusive upper bound.