Search code examples
c#stringbuilder

How do I get the last string appended to a StringBuilder?


In C#, I have a StringBuilder sb to which I am appending numerous times in for-loops.

Is there is a simple method for StringBuilders that spits out the last string that was appended to it?


Solution

  • Nope. You should probably use a list of strings and then later join it to replace the StringBuilder functionality like this:

    List<string> strings = new List<string>();
    strings.Add("...");
    string result = string.Join("", strings);
    

    Then you can access the most recently added string by accessing the last index of the string list or use the Last() LINQ extension like this:

    string lastString = strings.Last();