C# Queue<T>

C# Queue<T> 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<T> example

Let's see an example of generic Queue<T> class that stores elements using Enqueue() method, removes elements using Dequeue() method and iterates elements using for-each loop.

snippet
using System;
using System.Collections.Generic;

public class QueueExample
{
    public static void Main(string[] args)
    {
        Queue names = new Queue();
        names.Enqueue("Sonoo");
        names.Enqueue("Peter");
        names.Enqueue("James");
        names.Enqueue("Ratan");
        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:

Output
Sonoo Peter James Ratan Irfan Peek element: Sonoo Dequeue: Sonoo After Dequeue, Peek element: Peter
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents