Information Technology Reference
In-Depth Information
Example of a Nested Class
The following code fleshes out classes MyClass and MyCounter into a full program. MyCounter
implements an integer counter that starts at 0 and can be incremented using the ++ operator.
When the constructor for MyClass is called, it creates an instance of the nested class and assigns
the reference to the field. Figure 23-8 illustrates the structure of the objects in the code.
class MyClass
{
class MyCounter // Nested class
{
private int _Count = 0;
public int Count // Read-only property
{
get { return _Count; }
}
public static MyCounter operator++( MyCounter current )
{
current._Count++;
return current;
}
}
private MyCounter counter; // Field of nested class
public MyClass() { counter = new MyCounter(); } // Constructor
public int Incr() { return (counter++).Count; } // Increment method
public int GetValue() { return counter.Count; } // Get counter value.
}
class Program
{
static void Main( )
{
MyClass mc = new MyClass(); // Create object.
mc.Incr(); mc.Incr(); mc.Incr(); // Increment it.
mc.Incr(); mc.Incr(); mc.Incr(); // Increment it.
Console.WriteLine("Total: {0}", mc.GetValue()); // Print its value.
}
}
Search WWH ::




Custom Search