Properties (C# Programming Guide)
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.
In this example, the class TimePeriod
stores a time period. Internally the class stores the time in seconds, but a property called Hours
is provided that allows a client to specify a time in hours. The accessors for the Hours
property perform the conversion between hours and seconds.
Example
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
Output
Time in hours: 24
Properties Overview
Properties 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. For more information, see Accessor Accessibility.
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.
Related Sections
C# Language Specification
For more information, see the following sections in the C# Language Specification:
1.6.6.2 Properties
10.2.7.1 Member names reserved for properties
10.6 Properties
See Also
Reference
Using Properties (C# Programming Guide)
Indexers (C# Programming Guide)