Home
C#
StringWriter Class
Updated Feb 20, 2023
Dot Net Perls
StringWriter. This C# type is used with HtmlTextWriter. A StringWriter instance is required in the constructor. It helps with building up a string.
C# type notes. In code that uses StringWriter, you can also use the internal StringBuilder. This allows you to convert method return values to string types.
StringReader
StringBuilder
Example. Let's begin by looking at a program that uses StringWriter. This type is implemented with an internal StringBuilder, giving it excellent performance.
Start We declare a new StringWriter—which always has an internal StringBuilder. We use the StringWriter mainly for the HtmlTextWriter.
HtmlTextWriter
Info GetStringBuilder 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.
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");
    }
}
<div> Some text </div><div> Some text </div><div> Some text </div>
StringBuilder. We have shown that using StringBuilder as an argument is an excellent approach. There are minimal wasted CPU cycles due to excessive object creation.
Summary. We saw an example of StringWriter. When working with a buffer or StringBuilder, it is a good idea to always write to the same buffer. We try to avoid creating temporary strings.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 20, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen