Introduction: Queue in C#.Net with example

In this post, we will learn about Queue in C#.Net with example.Queue follows a first-in, first-out process.

Description:

In my previous posts I have explained various topics like Stack in C#.Net, HashSet in C#.Net,Get site visitor count in asp.net, Convert generic list to datatable in Asp.Net C#.Net, Abstract Class in C# with Example Now in this post, I will explain about Queue in C#.Net with example.



 

Useful Methods of Queue Class:

Some of the most and useful methods of stack are:

Enqueue(object obj)

This method adds an object to the end of the Queue.

Dequeue(object obj)

This method removes and returns the object at the beginning of the Queue.

Contains(object obj)

This method determines whether an element is in the Queue.

Clear()

This methods removes all elements from the Queue.

object[] ToArray()

This methods copies the Queue to a new array.

TrimToSize()

This method sets the capacity to the actual number of elements in the Queue.

Example

Now, Create one Console Application and write below lines of codes in Visual Studio.

 

using System;
using System.Collections;

namespace ConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Queue Demo code
            Queue _Color = new Queue();

            _Color.Enqueue("Red");   // Adding elements to queue.
            _Color.Enqueue("Green");
            _Color.Enqueue("Blue");

            Console.WriteLine("Current queue: ");
            foreach (string c in _Color) Console.Write(c + " ");

            Console.WriteLine();
            _Color.Enqueue("White");
            Console.WriteLine("Current queue: ");
            foreach (string c in _Color) Console.Write(c + " ");

            Console.WriteLine();
            Console.WriteLine("Removing some values ");
            string s = (string)_Color.Dequeue();
            Console.WriteLine("The removed value: {0}", s);            

            Console.WriteLine("Current queue: ");
            foreach (string c in _Color) Console.Write(c + " ");

            Console.ReadKey();
        }
    }
}

Queue in C#.Net with example

Queue


I hope you got an idea about Queue in C#.Net with example.
I would like to have feedback from my blog readers.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website