Question: We have all read about or heard about the stack class, but many of us have probably never found a reason to use the LIFO object. I am curious to hear of real world solutions that used this object and why. 

<http://msdn.microsoft.com/en-us/library/system.collections.stack.aspx>

I recently saw an example where a programmer used a stack to keep track of his current position while traversing a hierarchical data source. As he moved down the hierarchy, he pushed his position identifier on to the stack and as he moved back up he popped items off the stack. I thought this was a very efficent way to keep track of his current position in a mamoth hierarchy. I had never seen this before.

Anyone else have any examples?

Answer: 
I've used them to keep track of Undo and Redo actions.

I use an interface something like this:

```
interface ICommand
{
    void Execute();
    void Undo();
    string Description { get; }
}

```

Undo and Redo are both of type `Stack<ICommand>`. Then I create a concrete class for a given action. In the class's constructor, I pass in any information I'd need to hold on to. `Execute` does the action initially, and also redoes it; `Undo` undoes it, obviously. It works like this:

* Undo an action: Pop the Undo stack and add to the Redo stack.
* Redo an undone action: Pop the Redo stack and add to the Undo stack again.
* Perform a new action: Add to the Undo stack and clear the Redo stack (since the state is no longer consistent).

I found that you have to take care that you're really undoing what was done. For instance, say you have a UI with two listboxes, and each has five items in it. Your action might be to click a button to move everything on the left list to the right list (so it now has ten, and the left list has zero).

The undo action is *not* to move everything back; the undo action is to move back only the five you actually moved, and leave the others.
You can validate string inputs that require balanced tokens. Think LISP:

```
(+ (- 3 2) (+ (+ 4 5) 11))

```

When you hit an opening paren:

```
stack.Push("(")

```

Then when you hit a closing paren:

```
stack.Pop()

```

If there are any tokens left in your stack when you're done, it's not balanced.

You can get fancier and validate proper nesting in inputs like HTML. In a highly-contrived example:

```
//see opening body
stack.Push("body")

//see opening div
stack.Push("div")

//see opening p
stack.Push("p")

///see closing div
if(!stack.Pop().Equal("div")){
    //not balanced
}

```