13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>C#</strong> LANGUAGE SPECIFICATION}public string Caption {get {return caption;}set {if (caption != value) {caption = value;Repaint();}}}public override void Paint(Graphics g, Rectangle r) {// Painting code goes here}the Button control declares a public Caption property. The get accessor of the Caption property returns thestring stored in the private caption field. The set accessor checks if the new value is different from the currentvalue, 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 fieldand 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 accessorstring s = okButton.Caption; // Invokes get accessorHere, the set accessor is invoked by assigning a value to the property, and the get accessor is invoked byreferencing the property in an expression. end example]The get and set accessors of a property are not distinct members, and it is not possible to declare the accessorsof a property separately. [Note: As such, it is not possible for the two accessors of a read-write property to havedifferent accessibility. end note] [Example: The exampleclass A{private string name;public string Name {get { return name; }}public string Name {set { name = value; }}}// Error, duplicate member name// Error, duplicate member namedoes not declare a single read-write property. Rather, it declares two properties with the same name, one readonlyand one write-only. Since two members declared in the same class cannot have the same name, the examplecauses a compile-time error to occur. end example]When a derived class declares a property by the same name as an inherited property, the derived property hidesthe inherited property with respect to both reading and writing. [Example: In the exampleclass A{public int P {set {…}}}class B: A{new public int P {get {…}}}242

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!