C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: We declare a new StringWriter—which always has an internal StringBuilder. We use the StringWriter mainly for the HtmlTextWriter.
HtmlTextWriterGetStringBuilder: This method is used to pass a reference to the WriteMarkup method. StringBuilder is much more common than StringWriter.
Tip: It is best to reuse buffers and write one piece at a time. This avoids allocations and improves performance.
C# program that uses StringWriter
using System;
using System.IO;
using System.Text;
using System.Web.UI;
class Program
{
static void Main()
{
// Example string data
string[] arr = new string[]
{
"One",
"Two",
"Three"
};
// Write markup and strings to StringWriter
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
foreach (string item in arr)
{
writer.RenderBeginTag(HtmlTextWriterTag.Div);
// Send internal StringBuilder to markup method.
WriteMarkup(item, stringWriter.GetStringBuilder());
writer.RenderEndTag();
}
}
Console.WriteLine(stringWriter.ToString());
}
/// <summary>
/// Writes to StringBuilder parameter
/// </summary>
static void WriteMarkup(string sourceString, StringBuilder builder)
{
builder.Append("Some").Append(" text");
}
}
Output
<div>
Some text
</div><div>
Some text
</div><div>
Some text
</div>
Review: We combined several types—HtmlTextWriter, StringWriter and StringBuilder—into working, efficient code.