In this article, we will learn about the queue class in C#.
A queue represents a variable size first-in-first-out (FIFO) collection of instances of the same specified type.
Three main operations can be performed on a Queue and its elements:
<ul><li>Enqueue adds an element to the end of the Queue.</li>
<li>Dequeue removes the oldest element from the start of the Queue.</li>
<li>Peek returns the oldest element that is at the start of the Queue but does not remove it from the Queue.<li>
</ul>
<h4>Creating a Queue</h4>
<p>We create a Queue in C# using the following syntax:
Queue<T> q = new Queue<T>();
<T>
here denotes any datatype which we want to create a stack of.
Count
: This property gets the number of elements present in the stack.Enqueue(T)
: Adds an object to the end of the QueueDequeue()
: Removes and returns the object at the beginning of the QueuePeek()
: Returns the object at the beginning of the QueueContains(T)
: Determines whether an element is in the QueueClear()
: Removes all objects from the QueueDifferent Queue operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace QueueDemo {
class Example {
static void Main(string[] args) {
Queue q = new Queue ();
q.Enqueue(5);
q.Enqueue(5);
q.Enqueue(2);
q.Enqueue(9);
Console.WriteLine(q.Count); // Prints 4, the size of queue
Console.WriteLine(q.Peek()); // Prints 5, the oldest element
Console.WriteLine(q.Dequeue()); // Prints 5, then removes it
Console.WriteLine(q.Dequeue()); // Prints 5, then removes it
Console.WriteLine(st.Contains(5)); // Checks if 5 is present
Console.WriteLine(st.Contains(2)); // Checks if 2 is present
}
}
}
</code></pre>
Output:
4
5
5
5
False
True
Task
In the editor below, perform the different tasks as directed.