.Net Framework
C# Tutorial
C# Control Statement
C# Arrays
C# Object Class
C# Properties
C# Inheritance
C# Polymorphism
C# Abstraction
C# Strings
C# Exception Handling
C# File IO
C# Collections
C# Generics
C# Delegates
C# Reflection
Anonymous Function
C# Multithreading
C# Synchronization
C# Web Service
C# Misc
C# New Features
C# Programs
C# Interview Questions
ADO.NET Tutorial
ASP.NET Tutorial
C# Queue
C# Queue class is used to Enqueue and Dequeue elements. It uses the concept of Queue that arranges elements in FIFO (First In First Out) order. It can have duplicate elements. It is found in System.Collections.Generic namespace.
C# Queue example
Let's see an example of generic Queue class that stores elements using Enqueue() method, removes elements using Dequeue() method and iterates elements using for-each loop.
using System;
using System.Collections.Generic;
public class QueueExample
{
public static void Main(string[] args)
{
Queue names = new Queue();
names.Enqueue("Suil");
names.Enqueue("Anil ");
names.Enqueue("Mathew");
names.Enqueue("Puskar");
names.Enqueue("Irfan");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Dequeue: "+ names.Dequeue());
Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
}
}
using System.Collections.Generic;
public class QueueExample
{
public static void Main(string[] args)
{
Queue names = new Queue();
names.Enqueue("Suil");
names.Enqueue("Anil ");
names.Enqueue("Mathew");
names.Enqueue("Puskar");
names.Enqueue("Irfan");
foreach (string name in names)
{
Console.WriteLine(name);
}
Console.WriteLine("Peek element: "+names.Peek());
Console.WriteLine("Dequeue: "+ names.Dequeue());
Console.WriteLine("After Dequeue, Peek element: " + names.Peek());
}
}
Output
Sunil
Anil
Mathew
Puskar
Irfan
Peek element: Sunil
Dequeue: Sunil
After Dequeue, Peek element: Peter
Anil
Mathew
Puskar
Irfan
Peek element: Sunil
Dequeue: Sunil
After Dequeue, Peek element: Peter