Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Properties look like fields from the outside, but internally they
contain logic, like methods do. For example, you can’t tell by looking
at the following code whether CurrentPrice is a field or a property:
Stock msft = new Stock(); msft.CurrentPrice = 30; msft.CurrentPrice -= 3; Console.WriteLine (msft.CurrentPrice);
A property is declared like a field, but with a get/set
block added. Here’s how to implement CurrentPrice as a property:
public class Stock
{
decimal currentPrice; // The private "backing" field
public decimal CurrentPrice // The public property
{
get { return currentPrice; }
set { currentPrice = value; }
}
}
get and set denote property
accessors. The get accessor runs when the property is read.
It must return a value of the property’s type. The