c-sharp
  1. c-sharp-stringwriter

C# StringWriter

In C#, the StringWriter class is used to write text to a StringBuilder object by formatting and interchanging the values of objects in a string. StringWriter provides a way to accumulate formatted string output without having to write to a stream or file.

Syntax

The syntax for creating a StringWriter instance is as follows:

StringWriter sw = new StringWriter();

To write text to the StringWriter, use the Write or WriteLine methods of the StringWriter object.

sw.Write("This is a test. ");
sw.WriteLine("Hello, world!");

Example

Let's say we want to write a string and formatted text to a StringBuilder object using StringWriter. Here's how we can implement it:

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

sw.WriteLine("This is a test. {0} is my favorite number.", 42);

Console.WriteLine(sb.ToString());

Output

When we run the example code above, the output will be:

This is a test. 42 is my favorite number.

Explanation

In the example above, we created a StringBuilder object called "sb" and a StringWriter object called "sw" that writes text to the StringBuilder. We then used the WriteLine method of the StringWriter to write a string and formatted text to the StringBuilder.

Finally, we printed the contents of the StringBuilder to the console using the ToString method.

Use

StringWriter is useful when you need to write formatted text to a StringBuilder object instead of writing directly to a stream or file. This can be used for logging, generating reports, or any situation where you need to accumulate text output before writing it to a file or another output.

Important Points

  • StringWriter writes text to a StringBuilder object.
  • StringWriter can be used to accumulate formatted text output.
  • StringWriter provides a more efficient way to write formatted output to a StringBuilder object than concatenating strings.

Summary

In this tutorial, we discussed how to use StringWriter in C# to write text to a StringBuilder object. We covered the syntax, example, output, explanation, use, and important points of StringWriter in C#. With this knowledge, you can now use StringWriter in your C# code to accumulate formatted text output before writing it to a file or another output.

Published on: