BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The Stack Collection

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.

Other Stack Processing Methods

In addition to the LIFO processing methods, the Stack class provides other functionality for modifying and reading the collection. This enhances the collection with behaviours similar to those found in some other similar types.

Clear

The Clear method is used to empty the contents of a stack. The method requires no parameters.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");

Console.WriteLine("Count: {0}", breadcrumbs.Count);     // Outputs "Count: 3"
breadcrumbs.Clear();
Console.WriteLine("Count: {0}", breadcrumbs.Count);     // Outputs "Count: 0"

Contains

Often you will need to determine if an item exists within a stack but you will not want to pop every item from the stack in order to find it. The Contains method permits this by returning a Boolean value indicating if the object is present.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");

Console.WriteLine(breadcrumbs.Contains("Articles"));    // Outputs "True"
Console.WriteLine(breadcrumbs.Contains("SQL Server"));  // Outputs "False"

ToArray

A further method exists that permits a stack's contents to be read without disturbing the order of the items. In a similar manner to with an ArrayList, the objects in the stack can be extracted into an array. The stack itself is unaffected.

Stack breadcrumbs = new Stack();

breadcrumbs.Push("Home Page");
breadcrumbs.Push("Articles");
breadcrumbs.Push("C#");

// Copy items
object[] array = breadcrumbs.ToArray();

// List array items
foreach (object o in array)
{
    Console.WriteLine(o.ToString());
}

/* OUTPUT

C#
Articles
Home Page

*/

Creating a Thread-Safe Stack Wrapper

In the earlier article discussing collection interfaces, the concept of a thread-safe synchronised collection was described. In order to create a thread-safe Stack, a synchronised wrapper collection is generated using the static Synchronized method.

Stack myCollection = new Stack();
Stack myThreadSafe = Stack.Synchronized(myCollection);
Console.WriteLine(myThreadSafe.IsSynchronized);	            // Outputs "True"
17 June 2007