Search code examples
c#stringbuilder

What is the best way to copy a StringBuilder?


What is the best way (performance wise) to instantiate a new StringBuilder from another one? (Copy-Ctor).

I don't want to pass via an immutable string as the underline data is very big.

so the below is valid, but not wanted.

StringBuilder newSB = new StringBuilder(oldSB.ToString());

I want something like

StringBuilder newSB = new StringBuilder(oldSB);

But this is not supported.


Solution

  • There’s an overload of Append for other StringBuilder instances:

    var newSB = new StringBuilder(oldSB.Length);
    newSB.Append(oldSB);