Light Mode Image

C# Queue and Stack

Queue and Stack are two collection classes that are part of the System.Collections namespace. They represent data structures that follow the First-In-First-Out (FIFO) and Last-In-First-Out (LIFO) principles, respectively.

 

1. Queue

 

Queue is a collection of elements in which items are added at the end (enqueue) and removed from the beginning (dequeue). The Queue class in C# provides methods for adding, removing, and inspecting elements.

 

Example of a Queue in C#.

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        Queue myQueue = new Queue();

        // Enqueue elements
        myQueue.Enqueue("Item 1");
        myQueue.Enqueue("Item 2");
        myQueue.Enqueue("Item 3");

        // Dequeue elements
        while (myQueue.Count > 0)
        {
            Console.WriteLine(myQueue.Dequeue());
        }
    }
}

 

2. Stack

 

Stack is a collection of elements in which items are added and removed from the same end, commonly referred to as the "top" of the stack.

 

The Stack class in C# provides methods for pushing (adding) and popping (removing) elements.

 

Example of a Stack in C#.

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        Stack myStack = new Stack();

        // Push elements
        myStack.Push("Item 1");
        myStack.Push("Item 2");
        myStack.Push("Item 3");

        // Pop elements
        while (myStack.Count > 0)
        {
            Console.WriteLine(myStack.Pop());
        }
    }
}

 

Both Queue and Stack classes can hold elements of any data type, and they provide methods to check the count, clear the collection, and perform other common operations.

 

Choose between them based on whether you need a FIFO (Queue) or LIFO (Stack) behavior for your specific use case.