Reputation: 10140
In this code I try to appendFormat
a message with a length bigger than the string builder's capacity:
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder(10);
sb.AppendFormat("1234567890123"); // 13 characters
Console.WriteLine(sb.Capacity);
}
Do you know what should be the output (answer at the bottom)?
Okay, let's try to change this code and init StringBuilder
with capacity, still less than the string length, for example 12:
static void Main(string[] args)
{
StringBuilder sb = new StringBuilder(12);
sb.AppendFormat("1234567890123"); // 13 characters
Console.WriteLine(sb.Capacity);
}
So, my question is: does AppendFormat
really double
the start capacity of StringBuilder
if string couldn't be appened? If the appended string's length should be 24 characters, then the Capacity
will become 48
?
Output code: 20 & 24
Upvotes: 0
Views: 245
Reputation: 102743
does AppendFormat really double the start capacity of StringBuilder if the string couldn't be appended?
Yes -- see here.
Whenever the append operation causes the length of the StringBuilder object to exceed its capacity, its existing capacity is doubled and the Append operation succeeds.
Upvotes: 3