C# 3.0

Page 49

C# Feature—Access Modifiers At the physical level, a C# program consists of one or more compilation units, each contained in a separate source file. When a C# program is compiled, all of the compilation units are processed together. Thus, compilation units can depend on each other, possibly in a circular fashion. An assembly is a physical container for types and the resources associated with them. At the logical level, C# programs are organized using namespaces. Namespaces are used as a way of presenting program elements that are exposed to other programs in the same or different assemblies. Access modifiers are a way of specifying which members of a namespace will be exposed and to what degree. In C#, an access modifier alters the default accessibility of a type or its members. The available modifiers and the defaults that are applied are shown in Table 2-1. In this table, types include classes, structs, interfaces, enums, and delegates. The interpretation of this table for classes is as follows: • A non-nested class is by default visible to other classes in the same assembly. • A nested class is by default private and can have no more accessibility than its enclosing class. • A member of a class (e.g., field, method, property) is by default private. • An inherited class can have special access to a member in its superclass that has been tagged with the protected modifier. Unless you are going to do cross-assembly development, the public modifier is not strictly necessary; however, it has a currency in programming that the internal modifier does not. It is therefore acceptable to use public when tagging members for access outside of classes. The real need for the more restrictive internal modifier is illustrated in the “Example” section. There are some restrictions as to where and how access modifiers can be placed. Interface members are always public, and no modifiers are allowed. Namespaces cannot have private or protected members. Modifiers can only be added to types and members to make them as accessible as their enclosing methods or classes. cf. C# Language Specification Version 3.0, September 2007, Section 10.3.5

Example 2-3. Proxy pattern theory code 1 2 3 4 5 6 7 8 9 10

26 |

using System; // Proxy Pattern Judith Bishop // Shows virtual and protection proxies class SubjectAccessor { public interface ISubject { string Request ( ); }

Chapter 2: Structural Patterns: Decorator, Proxy, and Bridge

Dec 2006


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.