While appending strings to a StringBuilder
, can its Capacity and Length go beyond its MaxCapacity
?
According to MSDN MaxCapacity is defined as "The maximum number of characters string builder instance can hold". But this behaviour is inconsistent in below two code snippets:
Snippet 1:
In the below code ArgumentOutOfRangeException
is thrown when the length of the StringBuilder exceeds its MaxCapacity - This is as expected.
String str = sb.ToString();
StringBuilder sb1 = new StringBuilder(3, 5);
sb1.Append("1"); //no error as Length 1 <= max limit 5
sb1.Append("12"); //no error as Length 3 <= max limit 5
sb1.Append("123"); //ArgumentOutOfRangeException Thrown as Length 6 > max limit 5
Snippet 2:
In the below code NO ArgumentOutOfRangeException
is thrown when the length of the StringBuilder exceeds its MaxCapacity - This behaviour seems to be incorrect.
StringBuilder sb = new StringBuilder(3, 5);
sb.Append("1"); //no error as Length 1 <= max limit 5
sb.Append("2"); //no error as Length 2 <= max limit 5
sb.Append("3"); //no error as Length 3 <= max limit 5
sb.Append("4"); //no error as Length 4 <= max limit 5
sb.Append("5"); //no error as Length 5 <= max limit 5
sb.Append("6"); //Even though Length 6 > max limit 5 NO EXCEPTION IS THROWN
String str = sb.ToString(); //Contains "123456"
Can anyone please explain whats happening in these two cases and why is the difference in the behavior?
StringBuilder Constructor (Int32, Int32)
Notes to Callers
In the .NET Framework 4 and the .NET Framework 4.5, when you instantiate the StringBuilder object by calling the StringBuilder(Int32, Int32) constructor, both the length and the capacity of the StringBuilder instance can grow beyond the value of its MaxCapacity property. This can occur particularly when you call the Append and AppendFormat methods to append small strings.
Additional Resource:
StringBuilder
source code
Conclusion:
This class has written this way for performance reasons and as stated in official documents, its Capacity
and Length
can grow beyond the its MaxCapacity
particularly when appending small strings. Furthermore as stated in documents, some of default values are implementation-specific
and so It seems you better don't rely on Capacity
and MaxCapacity
, and only use this class for performance reasons these conditions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With