Just coding for a bit of fun and to get my head round anonymous methods, etc. I have a class whose main purpose is to run a lambda in a loop. The lambda has an out parameter (exit) which gets passed back into the class. Now I can nest these as per the code below where l2 is declared in the lambda for l1.
int outer = 0;
Loop l1 = new Loop().Infinite((out bool outerExit) =>
{
int inner = 0;
outer++;
Loop l2 = new Loop().Infinite((out bool innerExit) =>
{
inner++;
Debug.WriteLine($"{outer}-{inner}");
innerExit = inner >= 3;
outerExit = inner >= 3;
});
//outerExit = outer >= 3;
});
Assert.Equal(3, outer);
However this gives an error in the l2 lambda where i assign a value to outerExit.
Error CS1628 Cannot use ref, out, or in parameter 'outerExit' inside an anonymous method, lambda expression, query expression, or local function
The idea is to exit both Loops from within the inner loop when a certain criteria is met.
For those interested.
public class Loop
{
//this is a delegate TYPE!!! that matches our function
public delegate void ExitableAction<T1>(out T1 a);
//in thiscase it is a bool
protected ExitableAction<bool> action;
protected LoopType type;
public Loop Infinite(ExitableAction<bool> actn)
{
action = actn;
type = LoopType.Infinite;
Start();
return this;
}
protected void Start()
{
bool exit = false;
while(!exit)
{
action.Invoke(out exit);
}
}
}