Creating StringBuilder having specified capacity in C#

CsharpServer Side ProgrammingProgramming

To create StringBuilder having specified capacity, the code is as follows −

Example

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main(String[] args){
      StringBuilder strBuilder1 = new StringBuilder("Tim");
      StringBuilder strBuilder2 = new StringBuilder("Tom");
      StringBuilder strBuilder3 = new StringBuilder();
      StringBuilder strBuilder4 = new StringBuilder(5);
      strBuilder2 = strBuilder3;
      Console.WriteLine("Is StringBuilder3 equal to StringBuilder2? = "+strBuilder3.Equals(strBuilder2));
      Console.WriteLine("StringBuider1 capacity = "+strBuilder1.Capacity);
      Console.WriteLine("StringBuider2 capacity = "+strBuilder2.Capacity);
      Console.WriteLine("StringBuider3 capacity = "+strBuilder3.Capacity);
      Console.WriteLine("StringBuider4 capacity = "+strBuilder4.Capacity);
   }
}

Output

This will produce the following output −

Is StringBuilder3 equal to StringBuilder2? = True
StringBuider1 capacity = 16 
StringBuider2 capacity = 16 
StringBuider3 capacity = 16 
StringBuider4 capacity = 5

Example

Let us now see another example −

 Live Demo

using System;
using System.Text;
public class Demo {
   public static void Main(String[] args){
      StringBuilder strBuilder = new StringBuilder();
      Console.WriteLine("StringBuider capacity = "+strBuilder.Capacity);
      StringBuilder strBuilder2 = new StringBuilder(20);
      Console.WriteLine("StringBuider2 capacity = "+strBuilder2.Capacity);
   }
}

Output

This will produce the following output −

StringBuider capacity = 16 
StringBuider2 capacity = 20
raja
Published on 10-Dec-2019 12:03:18
Advertisements