TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# StringWriter Class

This C# example program uses the StringWriter type from System.IO. It uses StringBuilder as a buffer.

StringWriter is used with HtmlTextWriter.

A StringWriter instance is required in the constructor. In code that uses StringWriter, you can also use the internal StringBuilder. This allows you to convert method return values to string types.

HtmlTextWriter

Example. Let's begin by looking at a complete console program that uses StringWriter. The StringWriter type is implemented with an internal StringBuilder, giving it excellent performance in most scenarios involving looping.

Tip: For compatibility, we can directly use the internal buffer of the StringWriter.

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>

In the main method, we declare a new StringWriter—which always has an internal StringBuilder. We use the StringWriter mainly for the HtmlTextWriter. The HTML is written to the StringBuilder by HtmlTextWriter.

Next, the GetStringBuilder method is used to pass a reference to the WriteMarkup method. StringBuilder is much more common than StringWriter. This fact can improve compatibility with other methods.

Note: The WriteMarkup method could return a new string containing its results, but this would be very inefficient and non-ideal.

Instead: It is best to reuse buffers and write one piece at a time. This avoids allocations and improves performance.

StringBuilder. We have shown that using StringBuilder as an argument is an excellent approach—the approach presented above is an extension of that. There are minimal wasted CPU cycles due to excessive object creation.

Tip: Please see the StringBuilder page for more details. Many performance tips are available.

StringBuilder

Summary. We saw an example of StringWriter and its buffer in the C# language. When working with a buffer or StringBuilder, it is a good idea to always write new content to the same buffer. We try not to create temporary strings when not needed.

Review: We combined several types—HtmlTextWriter, StringWriter and StringBuilder—into working, efficient code.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf