C# Generic Queue<T> Tutorial with Programming Example

In this chapter you will learn:

  1. What is Queue<T> in C#?
  2. How to initialize it?
  3. Understand C# Queue with Programming Example

What is Queue<T>?

Queue Represents First In – First Out collection of objects. Let’s understand it with easy example. Take an example of line of ticket counter. The person which comes first take ticket first. All the person wait according to their insertion order in line and when they reach top of the line they get ticket. In C# programming, Queue<T> does the same thing. The item which is inserted first can be accessed first.

  • How to Initialize a Queue?

    You can initialize queue as follows:


    Properties Description
    Count Gets the number of elements contained in the Queue<T>.


    Methods Description
    Clear() Removes all objects from the Queue<T>.
    Contains(T) Determines whether an element is in the Queue<T>.
    CopyTo(T[], Int32) Copies the Queue<T> elements to an existing one-dimensional Array, starting at the specified array index.
    Dequeue() Removes and returns the object at the beginning of the Queue<T>.
    Enqueue(T) Adds an object to the end of the Queue<T>.
    Equals(Object) Determines whether the specified object is equal to the current object.(Inherited from Object.)
    Finalize() Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)
    GetEnumerator() Returns an enumerator that iterates through the Queue<T>.
    GetHashCode() Serves as the default hash function. (Inherited from Object.)
    GetType() Gets the Type of the current instance.(Inherited from Object.)
    MemberwiseClone() Creates a shallow copy of the current Object.(Inherited from Object.)
    Peek() Returns the object at the beginning of the Queue<T> without removing it.
    ToArray() Copies the Queue<T> elements to a new array.
    ToString() Returns a string that represents the current object.(Inherited from Object.)
    TrimExcess() Sets the capacity to the actual number of elements in the Queue<T>, if that number is less than 90 percent of current capacity.

    Programming Example


    Mark | Jack | Sarah | Smith | Robbie |
    Removing Mark from List.
    New list is :
    Jack | Sarah | Smith | Robbie |
    Printing City List
    Newyork | California | Las Vegas | Count3


    In this chapter you learned Queue<T> in C# with complete programming example. In the next chapter you will learn Stack<T> in C# Generics.

    Leave a Reply

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