Using Access Modifiers with Accessors


Beginning with C# 2.0, you can specify an access modifier, such as private, when declaring a get or set accessor. Doing so enables you to control access to an accessor. For example, you might want to make set private to prevent the value of a property or an indexer from being set by code outside its class. In this case, the property or indexer could be read by any code, but set only by a member of its class.

Here is an example:

 // Use an access modifier with an accessor. using System; class PropAccess {   int prop; // field being managed by MyProp   public PropAccess() { prop = 0; }   /* This is the property that supports access to      the private instance variable prop.  It allows      any code to obtain the value of prop, but      only other class members can set the value      of prop. */   public int MyProp {     get {       return prop;     }     private set { // now, private       prop = value;     }   }   // This class member increments the value of MyProp.   public void incrProp() {     MyProp++; // OK, in same class.   } } // Demonstrate accessor access modifier. class PropAccessDemo {   public static void Main() {     PropAccess ob = new PropAccess();     Console.WriteLine("Original value of ob.MyProp: " + ob.MyProp); //    ob.MyProp = 100; // can't access set     ob.incrProp();     Console.WriteLine("Value of ob.MyProp after increment: "                       + ob.MyProp);   } }

In the PropAccess class, the set accessor is specified private. This means that it can be accessed by other class members, such as incrProp( ), but cannot be accessed by code outside of PropAccess. This is why the attempt to assign ob.MyProp a value inside PropAccessDemo is commented out.

Here are some restrictions that apply to using access modifiers with accessors. First, only the set or the get accessor can be modified, not both. Furthermore, the access modifier must be more restrictive than the access level of the property or indexer. Finally, an access modifier cannot be used when declaring an accessor within an interface, or when implementing an accessor specified by an interface. (Interfaces are described in Chapter 12.)




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net