
.NET 1.1+The Stack Collection (2)
The forty-first part of the C# Fundamentals tutorial examines the Stack class. This collection includes the functionality required in a 'Last In, First Out' (LIFO) stacking structure. Stacks allow items to be held for later extraction and processing.
Using Stack Functions
Push Method
Stacks allow new items to be added to the top of the stack and later be extracted in the reverse order to their addition. To add a new item to the top of the stack, use the Push method. This method accepts one parameter, being the object to add to the stack.
Stack breadcrumbs = new Stack();
breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");
Console.WriteLine("Count: {0}", breadcrumbs.Count); // Outputs "Count: 3"
Pop Method
To retrieve items from a stack you call the Pop method. Pop returns the item from the top of the stack and removes it from the collection. The item is returned as an object that can be cast to the correct type. In the following example, the ToString method is used to perform the conversion as three items are added to and then retrieved from a stack. Not that the order of extraction is the reverse of the order in which the items were pushed onto the stack.
Stack breadcrumbs = new Stack();
breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");
while (breadcrumbs.Count != 0)
{
string next = breadcrumbs.Pop().ToString();
Console.WriteLine(next);
}
/* OUTPUT
C#
Articles
Home Page
*/
Peek Method
It can be useful to obtain the next item in a stack without removing it from the collection. The Peek method is used in the same manner as Pop but when the top item is retrieved, it is also left in position.
Stack breadcrumbs = new Stack();
breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");
string next = breadcrumbs.Peek().ToString();
Console.WriteLine(next); // Outputs "C#"
Console.WriteLine("Count: {0}", breadcrumbs.Count); // Outputs "Count: 3"
17 June 2007