Working with Queues and Stacks


Apart from Hashtables, queues and stacks are probably the most common Collection classes. With this article I will explain the ins and outs of queues and stacks.

Again with the Collections?

Yes. After you have seen how versatile the Collections Namespace is, you'll never again cringe with fear when you encounter it, and you will - many times!

What is a Queue?

When you go to a bank or a grocery store you have to stand in a queue for service. The first person in the queue is the first person helped. The last person in the queue is the last person helped. Agreed? Now, the Queue class works the same way. It is what is called a FIFO ( First in, First out ) list.

As this MSDN article mentions: Queues are useful for storing messages in the order they were received for sequential processing. This class implements a queue as a circular array. Objects stored in a Queue are inserted at one end and removed from the other.

What is a Stack?

A Stack is the opposite of a Queue. Where a Queue is a FIFO list, a Stack represents a LIFO (Last in, First out ) list. This analogy is the same as a stack of books. The first book you place on your desk, will remain at the bottom, whereas the last book that you have placed on the stack, will most likely be used / discarded first.

MSDN explains a Stack as: simple last-in-first-out (LIFO) non-generic collection of objects

Sample Programs

If you still find these two classes hard to understand, I have worked out samples for you. These samples are in VB.NET and C#. You are welcome following the next few steps in creating your project in your specific language ( VB.NET or C# ).


Our design is quite simple. It looks like the following picture:

Our design
Figure 1 - Our design


Add the necessary Namespace to your project.


Imports System.Collections

C# :

using System.Collections;

Next, our class level variables:


    Private qMyQueue As New Queue 'Our Queue object
    Private sMyStack As New Stack 'Our Stack Object

C# :

        private Queue qMyQueue = new Queue(); //Our Queue object
        private Stack sMyStack = new Stack(); //Our Stack Object

Store values inside the Queue object.


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        'Store values inside Queue
    End Sub

C# :

        private void Button1_Click(object sender, EventArgs e)
            //Store values inside Queue

Populate the Stack object:


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

        'Populate Stack Object
    End Sub

C# :

        private void Button2_Click(object sender, EventArgs e)
            //Populate Stack Object

This is where it gets interesting! Once we have our lists set up, there are numerous ways in which we can access the items inside the lists. With the Queue object we can use its Dequeue method. This will in effect release the first object added to the list, for example.


Console.WriteLine("(Dequeue) {0}", qMyQueue.Dequeue())

C# :

Console.WriteLine("(Dequeue) {0}", qMyQueue.Dequeue())

Would remove first from the list, next time it is called, second will be removed and so on.

With the Stack object we would need to use the Pop method.


Console.WriteLine("(Pop){0}", sMyStack.Pop())

C# :

Console.WriteLine("(Pop){0}", sMyStack.Pop());

The above code for the Stack object would remove the last item in the list, so in our example, third, then second, then first.

We could also make use of a loop to iterate through the Queue and Stack completely:


        While qMyQueue.Count > 0
            Dim obj As Object = qMyQueue.Dequeue
            Console.WriteLine("from Queue: {0}", obj)
        End While

        While sMyStack.Count > 0
            Dim obj As Object = sMyStack.Pop
            Console.WriteLine("from Stack: {0}", obj)
        End While

C# :

	while (qMyQueue.Count > 0) {
		object obj = qMyQueue.Dequeue;
		Console.WriteLine("from Queue: {0}", obj);

	while (sMyStack.Count > 0) {
		object obj = sMyStack.Pop;
		Console.WriteLine("from Stack: {0}", obj);

The IEnumerator Interface

I decided to mention this Interface here as I am trying to teach you how to use the Collection classes properly. The IEnumerator Interface provides a way for us to enumerate, or iterate, or simply, loop through the certain Collection class. It exposes methods such as MoveNext, which moves to the next item in the list, and Current, which shows the current item in the list. We need an IEnumerable Interface object so that it can expose (identify) the enumerator, which supports a simple iteration over a non-generic collection.

MSDN IEnumerator

MSDN IEnumerable

Let us add this functionality. Add the following procedure to your code.


    Public Sub DisplayValues(ByVal MyQueueCollection As IEnumerable, ByVal MyStackCollection As IEnumerable)

        Dim MyQueueEnumerator As IEnumerator = MyQueueCollection.GetEnumerator() 'Get list(s) to iterate through
        Dim MyStackEnumerator As IEnumerator = MyStackCollection.GetEnumerator()

        While MyQueueEnumerator.MoveNext() 'Move to next item

        End While

        While MyStackEnumerator.MoveNext()
            ListBox2.Items.Add(MyStackEnumerator.Current.ToString()) 'Display current item
        End While

    End Sub

C# :

        public void DisplayValues(IEnumerable MyQueueCollection, IEnumerable MyStackCollection)
            IEnumerator MyQueueEnumerator = MyQueueCollection.GetEnumerator(); //Get list(s) to iterate through
            IEnumerator MyStackEnumerator = MyStackCollection.GetEnumerator();

            while (MyQueueEnumerator.MoveNext()) //Move to next item


            while (MyStackEnumerator.MoveNext())
                ListBox2.Items.Add(MyStackEnumerator.Current.ToString()); //Display current item


Finally, add the call to this procedure inside Button3's Click event.


    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        DisplayValues(qMyQueue, sMyStack)
    End Sub

C# :

        private void Button3_Click(object sender, EventArgs e)
            DisplayValues(qMyQueue, sMyStack);

When the Show Values button is clicked, it would resemble Figure 2:

Values of both lists
Figure 2 - Values of both lists

Not so complicated now is it? Hopefully not. I am attaching working samples of these exercises for you, so play around with them and experiment - that is one of the best ways to learn.


Thanks for reading this article. I hope you have enjoyed it and benefited from it. Do not be scared of Collection anymore, they're quite easy! Until next time, cheers!

Related Articles



  • Cringes

    Posted by Hannes du Preez on 11/26/2012 03:13am

    Hi Dominic. Thanks a lot for reading and your honest feedback! I am involved with many online forums as well as give programming classes to students. I also work with many a professional programmers who always try to circumvent the collections namespaces - because they are scared of it. I can't tell you why they seem to be scared of it - perhaps not having the correct fundamentals of programming? Beats me. That is why I try to teach my students about things like this

  • A question about this article

    Posted by Dominic on 09/25/2012 05:06am

    I'm curious to know who "cringe[s] with fear when [they] encounter" the Collections namespace? It's widely used and its members are basic data structures that are seen in any entry level CS classes. I'd like to understand what are the motivations to do such an article series? Did you have requests for it? Did you have visitor feedback saying your previous articles were too advanced? I'm really curious about this... Thanks

    • I cringe

      Posted by Dam on 10/23/2012 09:04am

      I didn't know the collections namespace existed; I've been programming in .NET for 10 years. This article has opened my eyes.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Anthony Christie, the Chief Marketing Officer for Level Communications, is responsible for customer experience, worldwide marketing and product management. In this informative asset, he shares his insights into why a private network connection to cloud-bases applications is the right decision for your enterprise. Download now to find out more.

  • Enterprises are increasingly looking to platform as a service (PaaS) to lower their costs and speed their time to market for new applications. Developing, deploying, and managing applications in the cloud eliminates the time and expense of managing a physical infrastructure to support them. PaaS offerings must deliver additional long-term benefits, such as a lower total cost of ownership (TCO), rapid scalability, and ease of integration, all while providing robust security and availability. This report …

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date