C# Programming > Data

C# Data Structures

Stack, Queue

Stack

The Stack class is one of the many C# data structures that resembles an List. Like an List, a stack has an add and get method, with a slight difference in behavior.

To add to a stack data structure, you need to use the Push call, which is the Add equivalent of an List. Retrieving a value is slightly different. The stack has a Pop call, which returns and removes the last object added. If you want to check the top value in a Stack, use the Peek call.

The resulting behavior is what is called LIFO, which stands for Last-In-First-Out. This particular data structure is helpful when you need to retrace your steps so to speak.

There are two formats to define a Stack in C#:

Stack stack = new Stack();
Stack<string> stack = new Stack<string>();

The different between the data structures being that the simple Stack structure will work with Objects while the Stack<> one will accept only a specified object.

Here is the C# code to add and traverse through a Stack data structure:

Stack<string> stack = new Stack<string>();
stack.Push("1");
stack.Push("2");
stack.Push("3");

while (stack.Count > 0)
{
    MessageBox.Show(stack.Pop());
}

If you run the C# code you see that the list is returned in the order: 3, 2, 1.

Queue

Another one of the many C# data structures is the Queue. A Queue is very similar to the Stack data structure with one major difference.

Rather than follow a LIFO behavior, a Queue data structure goes by FIFO, which stands for First-In-First-Out. Whenever you submit an article to be approved on a website for example, the site adds your submittion to a queue. That way the first objects added are the first ones to be processed.

The Add call for a queue (or the Push version) is Enqueue:

queue.Enqueue("1");

The Remove call is Dequeue:

queue.Dequeue();

Similarly the Peek call allows you to view the top value without removing it. This specific data structure is very often used in conjucture with stack data structures.

Here is some simple C# code to add items to a queue and the transverse it:

Queue<string> queue = new Queue<string>();
queue.Enqueue("1");
queue.Enqueue("2");
queue.Enqueue("3");

while (queue.Count > 0)
{
   MessageBox.Show(queue.Dequeue());
}

Also keep in mind the queue data structure can be defined as a general Queue and as a type-specific Queue<>

Back to C# Data Structures - Page 1

Back to C# Article List