Free mag vol1 | Page 252

CHAPTER 5  UNDERSTANDING ENCAPSULATION polymorphic interface to all derived types (the Draw() method in this example), you can assume each member in the array has this functionality. Consider the following Main() method, which instructs an array of Shape-derived types to render themselves using the Draw() method: class Program { static void Main(string[] args) { Shape[] myShapes = new Shape[3]; myShapes[0] = new Hexagon(); myShapes[1] = new Circle(); myShapes[2] = new Hexagon(); } foreach (Shape s in myShapes) { // Use the polymorphic interface! s.Draw(); } Console.ReadLine(); } This wraps up our brisk overview of the pillars of OOP. Now that you have the theory in your mind, the remainder of this chapter explores further details of how encapsulation is handled under C#. Chapter 6 will tackle the details of inheritance and polymorphism. C# Access Modifiers When working with encapsulation, you must always take into account which aspects of a type are visible to various parts of your application. Specifically, types (classes, interfaces, structures, enumerations, and delegates) as well as their members (properties, methods, constructors, and fields) are defined using a specific keyword to control how “visible” the item is to other parts of your application. Although C# defines numerous keywords to control access, they differ on where they can be successfully applied (type or member). Table 5-1 documents the role of each access modifier and where it may be applied. Table 5-1. C# Access Modifiers 188 C# Access Modifier May Be Applied To Meaning in Life public Types or type members Public items have no access restrictions. A public member can be accessed from an object, as well as any derived class. A public type can be accessed from other external assemblies. private Type members or nested types Private items can only be accessed by the class (or structure) that defines the item.