Skip to content

Instantly share code, notes, and snippets.

@secretGeek
Last active August 16, 2019 21:10
Show Gist options
  • Save secretGeek/43b37e8e3304a80c15e58a58fdbdc352 to your computer and use it in GitHub Desktop.
Save secretGeek/43b37e8e3304a80c15e58a58fdbdc352 to your computer and use it in GitHub Desktop.
A new and better* way to write for loops in C#. (* .... it's not better)
// In this week's episode of "YOUR DOING IT WRONG"
void Main()
{
// The ** OLD ** keyword-heavy way to write a for loop.... nobody does this any more...
for (int i = 0; i < 12; i++)
{
Console.WriteLine(i);
}
// WHY memorise all that custom syntax, that *only* applies to `for` statements.
// MUCH better to have general principles that are used everywhere and just use those.
//The NEW way to write a for loop... uses the proprietary fforr function... no keywords!
fforr(() => 0, i => i < 12, i => ++i, (i) =>
{
Console.WriteLine(i);
});
}
public void fforr(Func<int> iCreator, Predicate<int> test, Func<int, int> incrementi, Action<int> doAction)
{
var i = iCreator();
while (test(i))
{
doAction(i);
i = incrementi(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment