I've read that the StringBuilder type has a limit (the default is 16 characters), and when you append some text to it, beyond its limit, a new instance is created with a higher limit and the data is copied to it. I tried that using the following code :
StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",16);
test.Append("ABC");
And the CIL generated for that was :
.maxstack 3
.locals init (class [mscorlib]System.Text.StringBuilder V_0)
IL_0000: nop
IL_0001: ldstr "ABCDEFGHIJKLMNOP"
IL_0006: ldc.i4.s 16
IL_0008: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(string, int32)
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldstr "ABC"
IL_0014: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
IL_0019: pop
IL_001a: ret
Setting the limit to, say, 32 :
StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",32);
test.Append("ABC");
Generated exactly the same IL code. What I expect is creating a new instance in the first case, and changing the value of the instance in the second case, which obviously didn't happen, any clue why?
All the fun stuff happens in this line:
IL_0014: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
This is where you make the call to the Append() method, but the IL you have posted does not contain the body of that method. Look in the source code for the StringBuilder class (it's released under a license that allows you to have a look), and see what happens within the Append() method.
Spoiler alert! A look at the source code of Append() will reveal that the internal buffer is indeed increased whenever the length of the concatenated string exeeds the current size of the buffer.
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