Grow Capacity of String Bulider in C#

Shervan360 1,011 Reputation points


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

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

            // 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

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

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.
7,002 questions
No comments
{count} votes

Accepted answer
  1. Castorix31 65,791 Reputation points

    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.
    No comments

0 additional answers

Sort by: Most helpful