[Solved] Can you determine the terminating boolean expression of a for loop dynamically?


You can replace the condition in a loop with a delegate. Something like this works:

int i = 0;
Func<bool> predicate = () => i < 5;
for (; predicate(); ++i)
     Console.WriteLine(i);

Just assign a different delegate to predicate if you want a different condition.

EDIT: This might be a clearer example:

Func<int, bool> countToFive = num => num < 5;
Func<int, bool> countToTen = num => num < 10;

var predicate = countToFive;

for (int i = 0; predicate(i); ++i)
    Console.WriteLine(i);

1

solved Can you determine the terminating boolean expression of a for loop dynamically?