Read and Write - Only ( Properties ) in C# This is highly observed in common scenariowhen a property definition contains the get and set accessors, that property can be read as well as written. To make a property read - only, you simply leave out the set accessor, like this:
public int ID { get { return _ID; } }
You can now read but not write values into the ID property: Console.WriteLine(c1.ID); //---OK--- c1.ID = 1234; //---Error--- Likewise, to make a property write - only, simply leave out the get accessor: public int ID { set { _ID = value; } } //You can now write but not read from the ID property: Console.WriteLine(c1.ID); //---Error--- c1.ID = 1234; //---OK---
You can also restrict the visibility of the get and set accessors. For example, the set accessor of a public property could be set to private to allow only members of the class to call the set accessor, but any class could call the get accessor. The following example demonstrates this: public int ID { get { return _ID; } private set { _ID = value; } }
In this code, the set accessor of the ID property is prefixed with the private keyword to restrict its visibility. That means that you now cannot assign a value to the ID property but you can access it: c.ID = 1234; //---error--- Console.WriteLine(c.ID); //---OK--- You can, however, access the ID property anywhere within the Contact class itself, such as in the Email property: public string Email { get { //... this.ID = 1234; //... } //... }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|