StringBuilder.EnsureCapacity() Method in C#


The StringBuilder.EnsureCapacity() method in C# is used to ensure that the capacity of this instance of StringBuilder is at least the specified value.

Syntax

The syntax is as follows −

public int EnsureCapacity (int capacity);

Above, the parameter capacity is the minimum capacity to ensure.

Example

Let us now see an example −

 Live Demo

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("jhbjhb");
      Console.WriteLine("String = "+strBuilder);
      Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity);
      strBuilder.EnsureCapacity(20);
      Console.WriteLine("StringBuilder capacity= "+strBuilder.Capacity);
      char[] arr = new char[5] {'a', 'b', 'c', 'd', 'e'};
      strBuilder.CopyTo(1, arr, 1, 3);
      Console.WriteLine("\nCopied String in char array...");
      Console.WriteLine(arr);
   }
}

Output

This will produce the following output −

String = jhbjhb
StringBuilder capacity= 16
StringBuilder capacity= 20
Copied String in char array...
ahbje

Example

Let us now see another example −

 Live Demo

using System;
using System.Text;
public class Demo{
   public static void Main(){
      StringBuilder strBuilder = new StringBuilder("Katie");
      Console.WriteLine("String = "+strBuilder);
      Console.WriteLine("\nStringBuilder capacity = "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(35);
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
      strBuilder.EnsureCapacity(0);
      strBuilder.Length = 0;
      Console.WriteLine("\nStringBuilder capacity= "+strBuilder.Capacity);
      Console.WriteLine("StringBuilder length = "+strBuilder.Length);
   }
}

Output

This will produce the following output −

String = Katie
StringBuilder capacity = 16
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 5
StringBuilder capacity= 35
StringBuilder length = 0
raja
Published on 03-Dec-2019 09:39:58
Advertisements