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 sb = new StringBuilder(0, 5);
, the second sample throws. – ArmesStringBuilder sb = new StringBuilder(3, 5); sb.Append("1"); sb.Append("21"); sb.Append("32"); sb.Append("4");
doesn't throw. – Armes