Grow Capacity of String Bulider in C#

Shervan360 1,481 Reputation points
2021-11-06T03:10:03.103+00:00

Hello,

While the capacity is 200 and the size of StringBuilder is just132, the StringBuilder has grown to 212. why?

 class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sb = new StringBuilder("Initial String. ", 200);
            int jumpCount = 10;
            string[] animals = {"goats", "cats", "pigs"};

            // print some basic stats about the StringBuilder
            Console.WriteLine($"Capacity: {sb.Capacity}; Length: {sb.Length}");

            // Add some strings to the builder using Append
            sb.Append("The quick brown fox ");
            sb.Append("jumps over the lazy dog.");

            // AppendLine can append a line ending
            sb.AppendLine();

            // AppendFormat can be used to append formatted strings
            sb.AppendFormat("He did this {0} times.", jumpCount);
            sb.AppendLine();

            // AppendJoin can iterate over a set of values
            sb.Append("He also jumped over ");
            sb.AppendJoin(",", animals);

            // Modify the content using Replace
            sb.Replace("fox", "cat");

            // Insert content at any index
            sb.Insert(0, "This is the ");

            Console.WriteLine($"Capacity: {sb.Capacity}; Length: {sb.Length}");

            // Convert to a single string
            Console.WriteLine(sb.ToString());
        }
    }

Capacity: 200; Length: 16
Capacity: 212; Length: 132
This is the Initial String. The quick brown cat jumps over the lazy dog.
He did this 10 times.
He also jumped over goats,cats,pigs

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,306 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 81,831 Reputation points
    2021-11-06T06:44:20.44+00:00

    You added 12 characters to the capacity with

    sb.Insert(0, "This is the ");
    

    From documentation :

        // ... Existing characters are shifted to make room for the new text.
        // The capacity is adjusted as needed. If value equals String.Empty, the
        // StringBuilder is not changed.
    
    0 comments No comments

0 additional answers

Sort by: Most helpful