A self-referential class contains a reference member that refers to an object of the same class type. For example, the class declaration in Fig. 19.1 defines the shell of a self-referential class named Node
. This type has two properties—Data
(an int
) and Next
(a Node
). Next
references another Node
object—that is, an object of the same type as the one being declared here, hence the term “self-referential class.” Next
is referred to as a link (like the links in a chain).
Self-referential objects can be linked together to form useful data structures, such as lists, queues, stacks and trees. Figure 19.2 illustrates two self-referential objects linked together to form a linked list. A backslash (representing a null
reference) is placed in the link member of the second self-referential object to indicate that the link does not refer to another object. The backslash is for illustration purposes; it does not correspond to the backslash character in C#. A null
link normally indicates the end of a data structure.
Not setting the link in the last node of a list to null
is a logic error.
Creating and maintaining dynamic data structures requires dynamic memory allocation—a program’s ability to obtain more memory space at execution time to hold new nodes and to release space no longer needed. As you learned in Section 10.8, C# programs do not explicitly release dynamically allocated memory—rather, the CLR performs automatic garbage collection.
The new
operator is essential to dynamic memory allocation. Operator new
takes as an operand the type of the object being dynamically allocated and returns a reference to an object of that type. For example, the statement
var nodeToAdd = new Node(10);
allocates the appropriate amount of memory to store a Node
, initializes it and stores a reference to this object in nodeToAdd
. If no memory is available, new
throws an OutOfMemoryException
. The constructor argument 10
specifies the Node
object’s data.
The following sections discuss lists, stacks, queues and trees. These data structures are created and maintained with dynamic memory allocation and self-referential classes.