Collection Classes in .net - the Stack
This is the sixth part of an article on collection classes in .net with C#. This part covers the Stack.
For the first part see http://www.audacs.co.uk/ViewPage.aspx?PageID=512
For the next part on the Queue see http://www.audacs.co.uk/ViewPage.aspx?PageID=519
The stack is a collection class of course and as it's name suggests works like a stack of objects. A useful analogy is a stack of plates. The last one placed on the stack is the first one to come off. Items are not added and removed from a stack usinng Add and Remove methods. Instead we use Push and Pop methods.
There are actually 2 stacks within the .net framework. The first one is the original stack and the second one is the Generic version. These are found as follows:
System.Collections.Stack
System.Collections.Generic.Stack
The use of both of these is pretty much the same other than one is strongly typed at compile time.
The following code shows a sample usage first with the original Stack and then with the generic one. The output is of course the same fro both programs.
Original Stack
Generic Stack
Program Output
Note that in the generic version then on the following line we don't need to cast to a string like we do in the originall version.
So that's really all there is to the Stack. Its real purpose is to make it easy to model solutions where the thing your are modelling with software works like a stack.
Finally you should be aware that a stack is often referred to as a LIFO structure where LIFO stands for Last In First Out.
For the next part on the Queue see http://www.audacs.co.uk/ViewPage.aspx?PageID=519