Open In App

C# | Queue<T>.TrimExcess Method with Examples

Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access to items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called Dequeue.
Queue<T>.TrimExcess Method is used to set the capacity to the actual number of elements in the Queue<T>, if that number is less than 90 percent of current capacity.

A queue is an unbounded data structure and there is no method available to calculate the capacity of Queue in C#. It is dynamic and depends on the system memory. This method is generally used in memory management of the large queue.
Queue Properties:



Syntax:

public void TrimExcess ();

Note:



Below given is an example to understand the implementation in a better way:

Example:




// C# code to set the capacity to the
// actual number of elements in the Queue
using System;
using System.Collections.Generic;
  
class GFG {
      
    // Driver code
    public static void Main()
    {
          
        // Creating a Queue of strings
        Queue<string> myQueue = new Queue<string>();
  
        // Inserting elements into Queue
        myQueue.Enqueue("1st");
        myQueue.Enqueue("2nd");
        myQueue.Enqueue("3rd");
        myQueue.Enqueue("4th");
        myQueue.Enqueue("5th");
  
        // To display number of elements in Queue
        Console.WriteLine(myQueue.Count);
          
        // Removing all the elements from Queue
        myQueue.Clear();
  
        // using TrimExcess method
        myQueue.TrimExcess();
  
        // To display number of elements in Queue
        Console.WriteLine(myQueue.Count);
    }
}

Output:
5
0

Reference:


Article Tags :
C#