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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stack
{
class GenericStack
{
static void Main()
{
System.Collections.Generic.Stack<string> films = new Stack<string>();
films.Push("Dead Poets Society");
films.Push("The good, the bad and the ugly");
films.Push("An unfinished life");
films.Push("Laurence of Arabia");
films.Push("The Matrix");
foreach (string film in films)
{
Console.WriteLine(film);
}
string poppedFilm = (string)films.Pop();
Console.WriteLine();
Console.WriteLine("popped film: " + poppedFilm);
Console.Read();
}
}
}
Generic Stack
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace Stack
{
class Program
{
static void Main(string[] args)
{
System.Collections.Stack films = new System.Collections.Stack();
films.Push("Dead Poets Society");
films.Push("The good, the bad and the ugly");
films.Push("An unfinished life");
films.Push("Laurence of Arabia");
films.Push("The Matrix");
foreach (string film in films)
{
Console.WriteLine(film);
}
string poppedFilm = films.Pop();
Console.WriteLine();
Console.WriteLine("popped film: " + poppedFilm);
Console.Read();
}
}
}
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.
string poppedFilm = films.Pop();
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