StringBuilder sb = new StringBuilder("test", 4);
sb.Append('\n');
sb.AppendLine("test1");
sb.AppendLine("test2");
sb.AppendLine("test3");
sb.AppendLine("test4");
looking on IL code there is only one newobj line, but I thought there should be more instances of StringBuilder class since it should increase its capacity by creating new object? Or I got it wrong?
// [3 1 - 3 49]
IL_0000: ldstr "test"
IL_0005: ldc.i4.4
IL_0006: newobj instance void [System.Runtime]System.Text.StringBuilder::.ctor(string, int32)
IL_000b: stloc.0 // sb
// [4 1 - 4 17]
IL_000c: ldloc.0 // sb
IL_000d: ldc.i4.s 10 // 0x0a
IL_000f: callvirt instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::Append(char)
IL_0014: pop
// [5 1 - 5 24]
IL_0015: ldloc.0 // sb
IL_0016: ldstr "test1"
IL_001b: callvirt instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::AppendLine(string)
IL_0020: pop
// [6 1 - 6 24]
IL_0021: ldloc.0 // sb
IL_0022: ldstr "test2"
IL_0027: callvirt instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::AppendLine(string)
IL_002c: pop
// [7 1 - 7 24]
IL_002d: ldloc.0 // sb
IL_002e: ldstr "test3"
IL_0033: callvirt instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::AppendLine(string)
IL_0038: pop
// [8 1 - 8 24]
IL_0039: ldloc.0 // sb
IL_003a: ldstr "test4"
IL_003f: callvirt instance class [System.Runtime]System.Text.StringBuilder [System.Runtime]System.Text.StringBuilder::AppendLine(string)
IL_0044: pop
IL_0045: ret
from Troelsen book about c#, translated paragraph by me: "If you add more characters than the specified limit, the StringBuilder object will copy its data to a new instance and increase the buffer size by the specified limit."
Asked a friend to provide original quote, here it is, page 89 "Pro C#10 with .Net 6":
If you append more characters than the specified limit, the StringBuilder object will copy its data into a new instance and grow the buffer by the specified limit.
StringBuilder?StringBuilderbeyond its currentCapacitywon't create a newStringBuilderobject. How could it? You wouldn't have a reference to it afterwards so you couldn't use it. What actually happens is new memory is allocated to store the additional text and that new memory is referenced by the existingStringBuilderobject.StringBuilders, but it's a very obscure implementation detail, so I'm not sure if this is what the book is referring to. Either way, this is not something that you can see by inspecting the IL of your C# code.