![]() |
VOOZH | about |
A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.
Key Features:
Example: This example demonstrates how to use a Queue in C# by enqueueing elements and then dequeuing them in FIFO (First-in-first-out ) order.
1 2 3 4
Queue class has four constructors which are used to create the queue which are as follows:
Letβs see how to create an Queue using Queue() constructor:
Step 1: Include System.Collections namespace in your program with the help of using keyword
using System.Collections;
Step 2: Create a Stack using Stack class
Queue q = new Queue();
1. Adding Elements: We use Enqueue() method to insert elements in a Queue.
Example: This example demonstrates how to create a queue in C# and add various elements to it using the Enqueue() method, then access and display the elements using a foreach loop.
Geeks geeksforgeeks 1 10
2. Remove Elements: The Queue class provides two different methods to remove elements and the methods are:
Example: This example displays the contents of the Queue before and after removal.
Initial queue: Geeks For Geeks For Updated queue after Dequeue: For Geeks For
3. Get the Topmost Element of the Queue: The Queue class provides two different methods to find the topmost element of the Queue and the methods are listed below:
Example: This example demonstrates how to peek at the topmost element of a Queue.
The frontmost element in the queue is: 10
4. Check the Availability of Elements in the Queue: Queue class provide Contains() method to check if the element is present in the Queue or not.
Example: This program demonstrates how to check if the specified element are present in a Queue using the contains() method.
The element 20 is present in the queue: True The element 100 is present in the queue: False
| Generic Queue | Non-Generic Queue |
|---|---|
| Generic queue is defined under System.Collections.Generic namespace. | Non-Generic queue is defined under System.Collections namespace. |
| Generic queue can only store same type of elements. | Non-Generic queue can store same type or different types of elements. |
| There is a need to define the type of the elements in the queue. | There is no need to define the type of the elements in the queue. |
| It is type- safe. | It is not type-safe. |