I asked a question earlier, but I don't think I was clear enough about the sort of answers I was hoping for, so let me provide a more concrete example:
class Program
{
private static bool State;
static void Main(string[] args)
{
State = false;
Console.WriteLine(And());
Console.ReadLine();
}
static bool And()
{
return Or() && C();
}
static bool Or()
{
return A() || AB();
}
static bool C()
{
return State;
}
static bool A()
{
return true;
}
static bool AB()
{
State = true;
return true;
}
}
The flow of this program looks like:
- And() gets called
- And() calls Or()
- Or() calls A()
- A() returns true
- Flow returns to Or(), which returns true (lazy evaluation)
- Flow returns to And(), And() calls C()
- C() returns false
- Flow returns to And(), which returns false
Now if Or() did not perform lazy evaluation (I change ||
to |
), the program will return true. However, I don't want AB() to executed unless the result of the entire parse fails (And() returns false).
So what I'd like to do, is somewhere in the Or() function, save the current state on a stack (static variable) so that if And() returns false, I can pop an item off the stack and try the alternative.
How would I accomplish this in C#?