Stacks & Queues in C#

Stack and Queue collections in C# represent Stack and Queue data structures. A stack stores elements in the form of last in, first out. This means that the elements the item that is inserted at the end will be retrieved first. The term used for adding item into stack is called pushing while retrieving item is called popping.

A Queue class stores item on the basis of first in and first out principle. This means that the item which is inserted first is retrieved first while the item inserted at the end will be retrieved last. Adding item into the queue is called enqueue while while retrieving item from is called dequeue.

Have a look at Examples of Stack and Queue in C#

Stack

´╗┐using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            Stack st = new Stack();

            //pushing elements in a stack
            st.Push("BMW");
            st.Push("Ford");
            st.Push("Toyota");
            st.Push("Honda");
            st.Push("Suzuki");

            // popping elements from stack

            Console.WriteLine(st.Pop());
            Console.WriteLine(st.Pop());
            Console.WriteLine(st.Pop());

            //Clearing a stack
            st.Clear();

            Console.ReadKey();
        } 
    }
}

Download the code

In the above code a Stack object st has been created and some car names have been added to it. Now, if Pop method is called on the Stack object, the name of the cars will be displayed in their reverse order of insertion. This ascertains the fact that Stack class in C# follows last-in,first-out principle.

C# Queue

´╗┐using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            Queue qu = new Queue();

            //en-queueing items in the queue
            qu.Enqueue("BMW");
            qu.Enqueue("Ford");
            qu.Enqueue("Toyota");
            qu.Enqueue("Honda");
            qu.Enqueue("Suzuki");

            // de-queueing items from the queue
            Console.WriteLine(qu.Dequeue());
            Console.WriteLine(qu.Dequeue());
            Console.WriteLine(qu.Dequeue());

            //Clearing a queue
            qu.Clear();
            Console.ReadKey();
        } 
    }
}

Download the code

In the above code, names of different cars are stored in Queue object via Enqueue method. Now if the objects are retrieved from queue via Dequeue methods, they will be returned in the ascending order of insertion. This proves that Queue class in C# follows first-in, first-out principle.

<<< Hashtable and SortedList in C#Multi-threaded Programming in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .