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

Nested Classes

In C# it is possible to define one class inside another. A class defined inside another one is called a nested class .

Consider the following C# code fragment:

public class A
    int y;

    public static class B
	int x;

	void F() {}
This fragment defines the class A which contains the nested class B.

A nested class behaves like any ``outer'' class. It may contain methods and fields, and it may be instantiated like this:

A.B obj = new A.B ();
This statement creates an new instance of the nested class B. Given such an instance, we can invoke the F method in the usual way:

Note, it is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.

The methods of a nested class may access all the members (fields or methods) of the nested class but they can access only static members (fields or methods) of the outer class. Thus, F can access the field x, but it cannot access the field y.

next up previous contents index

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