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.

Chapter 17 Classesthe P property in B hides the P property in A with respect to both reading and writing. Thus, in the statementsB b = new B();b.P = 1; // Error, B.P is read-only((A)b).P = 1; // Ok, reference to A.Pthe assignment to b.P causes a compile-time error to be reported, since the read-only P property in B hides thewrite-only P property in A. Note, however, that a cast can be used to access the hidden P property. end example]Unlike public fields, properties provide a separation between an object’s internal state and its public interface.[Example: Consider the example:class Label{private int x, y;private string caption;public Label(int x, int y, string caption) {this.x = x;this.y = y;this.caption = caption;}public int X {get { return x; }}public int Y {get { return y; }}public Point Location {get { return new Point(x, y); }}public string Caption {get { return caption; }}}Here, the Label class uses two int fields, x and y, to store its location. The location is publicly exposed both asan X and a Y property and as a Location property of type Point. If, in a future version of Label, it becomesmore convenient to store the location as a Point internally, the change can be made without affecting the publicinterface of the class:class Label{private Point location;private string caption;public Label(int x, int y, string caption) {this.location = new Point(x, y);this.caption = caption;}public int X {get { return location.x; }}public int Y {get { return location.y; }}public Point Location {get { return location; }}public string Caption {get { return caption; }}}243

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

Saved successfully!

Ooh no, something went wrong!