Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

The AbstractContainer Class ToString Method

One of the methods defined in the C# object class is the ToString method. Consequently, every C# object supports the ToString method. The ToString method is required to return a string that represents the object ``textually.'' It is typically invoked in situations where it is necessary to print out the representation of an object.

Program gif defines the ToString method of the AbstractContainer class. This method is provided to simplify the implementation of classes derived from the AbstractContainer class. The default behavior is to print out the name of the class and then to print each of the elements in the container, by using the Accept method together with a visitor.

   program4742
Program: AbstractContainer class ToString method.

The ToString method makes use of a StringBuilder to accumulate the textual representations of the objects in the container. A C# string builder is like a C# string, except it can be modified. In particular, the StringBuilder class defines various Append methods that can be used to append text to the builder.

In this case, we use a visitor to do the appending. That is, the Visit method appends to the string builder the textual representation of every object that it visits. (It also makes sure to put in commas as required).

The final result returned by the ToString method consists of the name of the container class, followed by a comma-separated list of the contents of that container enclosed in braces { and }.


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.