Today I was looking at some very simple code yet was puzzled: Why was the StringBuilder truncating the string?
I quickly realized that this was happening due to the .Length Property. When this Property is adjusted on a StringBuilder with text in it, if the Length is set smaller then the contents it will truncate the text down to the specified length. Lets look at this simple example:
Example:
StringBuilder sb = new StringBuilder(5); // .Length = 5
sb.Append("123456"); // Extends the .Length to 6
sb.Length = 2; // Truncates everything down to two characters
(Capacity property remains set to the capacity at maximum which was 6)
This behavior is actually described in the MSDN Documentation for the Length property, but I never read it before today.
Here is the official MSDN quoted text:
If the specified length is less than the current length, the current StringBuilder object is truncated to the specified length. If the specified length is greater than the current length, the end of the string value of the current StringBuilder object is padded with the Unicode NULL character (U+0000).


0 comments:
Post a Comment