CSharp/C# Tutorial - C# Properties






Properties look like fields from the outside, but internally they contain logic.

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 Product {
    decimal currentPrice;       // The private "backing" field
   //  w  w  w .j  av a 2  s .c om
    public decimal CurrentPrice // The public property 
    { 
        get { 
           return currentPrice; 
        } 
        set { 
           currentPrice = value; 
        } 
    } 
} 

get and set are property accessors.

The get accessor runs when the property is read. It must return a value of the property's type.

The set accessor runs when the property is assigned.
It has an implicit parameter named value of the property's type that you typically assign to a private field.

We can write code for properties to control getting and setting its value.

Properties allow the following modifiers:

ItemModifier
Static modifierstatic
Access modifierspublic internal private protected
Inheritance modifiersnew virtual abstract override sealed
Unmanaged code modifiersunsafe extern




Read-only and calculated properties

A property is read-only if it specifies only a get accessor.

A property is write-only if it specifies only a set accessor.

A property typically has a dedicated backing field to store the underlying data.

However, a property can also be computed from other data. For example:



decimal currentPrice, sharesOwned; 
public decimal Worth {
   get { return currentPrice * sharesOwned; } 
} 




Automatic properties

An automatic property declaration instructs the compiler to provide the implementation.

We can redeclare the first example in this section as follows:


public class Product 
{
    public decimal CurrentPrice { get; set; } 

} 

The compiler automatically generates a private backing field of a compiler-generated name that cannot be referred to.

The set accessor can be marked private if you want to expose the property as read-only to other types.

get and set accessibility

The get and set accessors can have different access levels.


public class Product {
    private decimal x;
    public decimal X{
      get { //from  w  w w .  jav  a 2s  .c om
          return x; 
      } 
      private set { 
          x = Math.Round (value, 2); 
      } 
    } 
}