C# Stacks And Queues

C# Code Snippets Queue and Stack


In this code snippet, we’ll take a look at queues and stacks in C#.

Stacks and queues are similar to lists in the way that they don’t require their size to be declared on creation and elements can be dynamically added or removed. In fact, all of the above(queues, stacks, and lists) are part of the same collections namespace and implement some of the same interfaces

But unlike lists stacks work according to the LIFO(Last In First Out) concept. Simply put the first item you add or push on to the stack will be the last item to get removed or popped off the stack.

Queues on the other hand work according to the FIFO(First In First Out) concept. The first item to get added or enqueued will also be the first one to get removed or dequeued.

Let’s look at the code example below.


using System;
using System.Collections.Generic;

namespace QueueAndStack
    class Program
        static void Main(string[] args)
            //Queue is FIFO(First In First Out).
            Queue<MyClass> myQueue = new Queue<MyClass>();

            //Stack is LIFO(Last In First Out)
            Stack<MyClass> myStack = new Stack<MyClass>();

            //Add items to queue by enqueueing them.
            myQueue.Enqueue(new MyClass("1"));
            myQueue.Enqueue(new MyClass("2"));
            myQueue.Enqueue(new MyClass("3"));

            //Add items to stack by pushing them on.
            myStack.Push(new MyClass("1"));
            myStack.Push(new MyClass("2"));
            myStack.Push(new MyClass("3"));

            //Peek() is a useful method as it just looks at the value without removing the item.
            Console.WriteLine("Peek queue: ");

            Console.WriteLine("Peek stack: ");

            //Dequeue() removes the first item in queue and returns it.
            Console.WriteLine("Dequeue: ");

            //Pop() removes the last item on the stack and returns it.
            Console.WriteLine("Pop: ");

            //As you will be able to see the items were removed after dequeueing/poping.
            foreach (MyClass item in myQueue)
                Console.WriteLine("Queue: " + item.Text);


            foreach (MyClass item in myStack)
                Console.WriteLine("Stack: " + item.Text);


    class MyClass
        public MyClass(string text)
            Text = text;

        public string Text { get; set; }

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger