Classes are given meaning by their methods and properties. Methods are actions—verbs—that describe what the type can do or have done to it. Properties, on the other hand, are attributes—adjectives—that help describe the type.
Properties come in three different flavors: read-only,
write-only, and read-write. A property getter is defined with the
get keyword and returns
the property value, whereas a property setter,
defined with the
set keyword, updates
the property value.
The syntax for defining a read-only property is simply a method
with no arguments. For more explicit control, you can provide
with get and
with set methods.
Example 5-8 shows creating a
simple read-only property as well as a more complex property with both a
getter and a setter. To invoke the setter, use the left arrow operator,
<-, as if setting a mutable value.
Example 5-8. Defining class properties
> // Define a WaterBottle type with two properties [<Measure>] type ml type WaterBottle() = let mutable m_amount = 0.0<ml> // Read-only property
member this.Empty= (m_amount = 0.0<ml>) // Read-write property
member this.Amount with get ()= m_amount
and set newAmt= m_amount <- newAmt;; [<Measure>] type ml type WaterBottle = class new : unit -> WaterBottle member Amount : float<ml> member Empty : bool member Amount : float<ml> with set end > let bottle = new WaterBottle();; val bottle : WaterBottle > bottle.Empty;; val it : bool = true > bottle.Amount <- 1000.0<ml>;; val it : unit = () ...