Open In App
Related Articles

StringBuilder.EnsureCapacity() Method in C#

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
The EnsureCapacity(Int32) method of StringBuilder class helps us to ensures the capacity is at least equal to the specified value that is passed as the parameter to the method. If the current capacity is less than the capacity parameter, memory for this instance is reallocated to hold at least capacity number of characters; otherwise, no memory is changed.
Syntax: public int EnsureCapacity (int capacity); Here, the capacity is the minimum capacity to ensure. Return Value: It returns the new capacity of the current instance.
Exception: This method will give ArgumentOutOfRangeException if the capacity is less than zero or the Enlarging the value of this instance would exceed MaxCapacity. Example 1:
// C# program to demonstrate
// the EnsureCapacity Method
using System;
using System.Text;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // create a StringBuilder object
        StringBuilder str = new StringBuilder();
  
        // print string capacity
        Console.WriteLine("Before EnsureCapacity "
                          + "method capacity = "
                          + str.Capacity);
  
        // apply ensureCapacity()
        str.EnsureCapacity(18);
  
        // print string capacity
        Console.WriteLine("After EnsureCapacity"
                          + " method capacity = "
                          + str.Capacity);
    }
}

                    
Output:
Before EnsureCapacity method capacity = 16
After EnsureCapacity method capacity = 18
Example 2:
// C# program to demonstrate
// the EnsureCapacity Method
using System;
using System.Text;
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // create a StringBuilder object
        StringBuilder str = new StringBuilder();
  
        // print string capacity
        Console.WriteLine("Before EnsureCapacity "
                          + "method capacity = "
                          + str.Capacity);
  
        // apply ensureCapacity()
        str.EnsureCapacity(44);
  
        // print string capacity
        Console.WriteLine("After EnsureCapacity"
                          + " method capacity = "
                          + str.Capacity);
    }
}

                    
Output:
Before EnsureCapacity method capacity = 16
After EnsureCapacity method capacity = 44
Reference:

Last Updated : 28 Jan, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads