concept StringWriter in category c#

appears as: StringWriter
Code like a Pro in C#

This is an excerpt from Manning's book Code like a Pro in C#.

By instantiating our instance of type StringWriter (a data stream dealing with strings) and hanging onto a reference to that variable while using it as the Console’s output stream, we can grab the history data pretty easily. Instead of writing to some intangible output stream, the Console.WriteLine method writes to our StringWriter. Take note that some programming languages such as Java distinguish between input and output streams on a type level. C# does not do this. You can use any Stream derived class as an input or output stream.

Figure 9.5 When redirecting Console output to a StringWriter instance, the Output and Error streams write to the StringWriter instance instead of the regular Console output. The lifecycle from Figure 9.4 turns into: First, keyboard input (1) is sent to the Input Stream (2). Then some processing is done inside the application (this can be anything you want). Following processing, if an exception was thrown, the error is written to the Error Stream (3). If no exception, information is written to the Output Stream (3). Finally, the Error and Output streams are written to our StringWriter instance (4).

The Stream base class is the foundation for all data streams. Stream is an abstract class and the base class for many derived classes (such as StringWriter) that deal with a sequence of bytes. A StringWriter is a stream that deals with a sequence of bytes and exposes functionalities based on those bytes representing strings (and because, under the hood, a string is an array of characters: therefore characters). Since you typically write continuously to a stream, which makes it hard for the garbage collection to know when it can collect on a stream, the Stream class implements the IDisposable interface. As all derived classes from Stream implement the IDisposable interface, we need to clean up the instantiated Stream once we are done with it or risk a memory leak.