Properties in C# / Get and Set Methods in C#
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
class ClsTea
{
private string _locale;
public string Locale
{
get { return _locale; }
set { _locale = value; }
}
}
The following code sets the property and then gets it back
ClsTea MyTea = new ClsTea();
MyTea.Locale = "Ooty";
Console.WriteLine("British Tea is exported from " + MyTea.Locale);
- Proper
- ties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
- A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.
- The value keyword is used to define the value being assigned by the set indexer.
- Properties that do not implement a set method are read only.
- For simple properties that require no custom accessor code, consider the option of using auto-implemented properties.
No comments:
Post a Comment