StringWriter or StringBuilder

后端 未结 7 1873
盖世英雄少女心
盖世英雄少女心 2020-12-08 00:17

What is the difference between StringWriter and StringBuilder and when should I use one or the other?

相关标签:
7条回答
  • 2020-12-08 00:36

    Building on the previous (good) answers, StringWriter is actually much more versatile than StringBuilder, providing lots of overloads.

    For example:

    While Stringbuilder only accepts a string or nothing for Appendline

    StringBuilder sb = new StringBuilder();
    sb.AppendLine("A string");
    

    StringWriter can take a string format directly

    StringWriter sw = new StringWriter();
    sw.WriteLine("A formatted string {0}", DateTime.Now);
    

    With StringBuilder one must do this (or use string.Format, or $"")

    sb.AppendFormat("A formatted string {0}", DateTime.Now);
    sb.AppendLine();
    

    Not do or die stuff, but still a difference

    0 讨论(0)
提交回复
热议问题