X hits on this document

1007 views

0 shares

0 downloads

0 comments

246 / 396

Chapter ‎18   Unsafe code

the Button control declares a public Caption property. The get accessor of the Caption property returns the string stored in the private caption field. The set accessor checks if the new value is different from the current value, and if so, it stores the new value and repaints the control. Properties often follow the pattern shown above: The get accessor simply returns a value stored in a private field, and the set accessor modifies that private field and then performs any additional actions required to fully update the state of the object.

Given the Button class above, the following is an example of use of the Caption property:

Button okButton = new Button(); okButton.Caption = "OK";// Invokes set accessor string s = okButton.Caption;// Invokes get accessor

Here, the set accessor is invoked by assigning a value to the property, and the get accessor is invoked by referencing the property in an expression.

The get and set accessors of a property are not distinct members, and it is not possible to declare the accessors of a property separately. As such, it is not possible for the two accessors of a read-write property to have different accessibility. The example

class A { private string name;

public string Name {// Error, duplicate member name get { return name; } }

public string Name {// Error, duplicate member name set { name = value; } } }

does not declare a single read-write property. Rather, it declares two properties with the same name, one read-only and one write-only. Since two members declared in the same class cannot have the same name, the example causes a compile-time error to occur.

When a derived class declares a property by the same name as an inherited property, the derived property hides the inherited property with respect to both reading and writing. In the example

class A { public int P { set {...} } }

class B: A { new public int P { get {...} } }

the P property in B hides the P property in A with respect to both reading and writing. Thus, in the statements

B b = new B(); b.P = 1;// Error, B.P is read-only ((A)b).P = 1;// Ok, reference to A.P

the assignment to b.P causes a compile-time error to be reported, since the read-only P property in B hides the write-only P property in A. Note, however, that a cast can be used to access the hidden P property.

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.233

Document info
Document views1007
Page views1007
Page last viewedFri Dec 09 14:12:15 UTC 2016
Pages396
Paragraphs9401
Words133190

Comments