Properties
Similar to fields but give more control to getting and setting value without exposing internal details to the user property. Get accessor runs when property is read, returns a value.
Set accessor is to assign to property, and has implicit parameter named value.
public class Stock
{
decimal currentPrice; // The private "backing" field
public decimal CurrentPrice // The public property
{
get { return currentPrice; }
set { currentPrice = value; }
}
}
Modifiers
- Static : static
- Access modifiers: public, internal, private, protected
- Inheritance modifiers: new, virtual, abstract, override, sealed
- Unmanaged: unsage, extern
Read-only and calculated properties
- A property is read-only if it specifies only a get accessor.
- A property typically has a dedicated backing field to store the underlying data.
- Property can also be computed from other data.
decimal currentPrice, sharesOwned;
public decimal Worth
{
get { return currentPrice * sharesOwned; }
}
Expression-bodied properties
Expression-bodied property can declare read-only property.
public decimal Worth => currentPrice * sharesOwned;
Automatic properties
An automatic property declaration instructs the compiler to provide this implementation. The compiler automatically generates private backing field that cannot be referred.
public class Stock
{
...
public decimal CurrentPrice { get; set; }
}
Property initializers (C# 6)
You can add a property initializer to automatic properties.
public decimal CurrentPrice { get; set; } = 123;
Properties with an initializer can be read-only
public int Maximum { get; } = 999;
get and set accessibility
The get and set accessors can have different access levels.
public class Foo
{
private decimal x;
public decimal X
{
get { return x; }
private set { x = Math.Round (value, 2); }
}
}
CLR property implementation
property accessors internally compile to methods called get_XXX and set_XXX:
public decimal get_CurrentPrice {...}
public void set_CurrentPrice (decimal value) {...}