Open In App

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

Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item.
Stack<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 stack is an unbounded data structure and there is no method available to calculate the capacity of Stack in C#. It is dynamic and depends on the system memory. This method is generally used in memory management of the large Stack.



Stack Properties:

Syntax:



public void TrimExcess ();

Note:

Example:




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

Output:
5
0

Reference:


Article Tags :
C#