Nesting Classes

Classes have members, and it is entirely possible for the member of a class to be another user-defined type. Thus, a Button class might have a member of type Location, and a Location class might contain members of type Point. Finally, Point might contain members of type int.

At times, the contained class might exist only to serve the outer class, and there might be no reason for it to be otherwise visible. (In short, the contained class acts as a helper class.) You can define the helper class within the definition of the outer class. The contained, inner class is called a nested class, and the class that contains it is called, simply, the outer class.

Nested classes have the advantage of access to all the members of the outer class. A method of a nested class can access private members of the outer class.

In addition, the nested class can be hidden from all other classes—that is, it can be private to the outer class.

Finally, a nested class that is public is accessed within the scope of the outer class. If Outer is the outer class, and Nested is the (public) inner class, you refer to Nested as Outer.Nested, with the outer class acting (more or less) as a namespace or scope.

Tip

Java programmers take note: nested classes are roughly equivalent to static inner classes; there is no C# equivalent to Java’s nonstatic inner classes.

Example 5-6 adds a nested class to Fraction named FractionArtist. The job of FractionArtist is to render the fraction on the console. In ...

Get Programming C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.