Free mag vol1 | Page 289

CHAPTER 6  UNDERSTANDING INHERITANCE AND POLYMORPHISM } ... } In the following updated Main() method, notice how you can interact with the internal BenefitsPackage type defined by the Employee type: static void Main(string[] args) { Console.WriteLine("***** The Employee Class Hierarchy *****\n"); ... Manager chucky = new Manager("Chucky", 50, 92, 100000, "333-23-2322", 9000); double cost = chucky.GetBenefitCost(); Console.ReadLine(); } Understanding Nested Type Definitions Chapter 5 briefly mentioned the concept of nested types, which is a spin on the “has-a” relationship you have just examined. In C# (as well as other .NET languages), it is possible to define a type (enum, class, interface, struct, or delegate) directly within the scope of a class or structure. When you have done so, the nested (or “inner”) type is considered a member of the nesting (or “outer”) class, and in the eyes of the runtime can be manipulated like any other member (fields, properties, methods, and events). The syntax used to nest a type is quite straightforward: public class OuterClass { // A public nested type can be used by anybody. public class PublicInnerClass {} } // A private nested type can only be used by members // of the containing class. private class PrivateInnerClass {} Although the syntax is fairly clear, understanding why you would want to do this might not be readily apparent. To understand this technique, ponder the following traits of nesting a type: • Nested types allow you to gain complete control over the access level of the inner type, as they may be declared privately (recall that non-nested classes cannot be declared using the private keyword). • Because a nested type is a member of the containing class, it can access private members of the containing class. • Often, a nested type is only useful as a helper for the outer class, and is not intended for use by the outside world. When a type nests another class type, it can create member variables of the type, just as it would for any point of data. However, if you want to make use of a nested type from outside of the containing type, you must qualify it by the scope of the nesting type. Consider the following code: 226