C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Field: The "mutable size" is a field on the Animal type. It is initialized to the value passed to the Animal at creation time.
Do: When initialized, the Animal will execute its "do" statements. Here it prints a helpful message.
Member: The Weight is a method on the Animal. It returns an int. It returns the size times 10.
F# program that uses type, member
type Animal(s : int) =
// Store the argument in the object.
let mutable size = s
// Write a helpful message.
do printfn "Animal created, size = %A" size
// For Weight, return size times 10, an int.
member x.Weight : int = size * 10
// Create an Animal with size 5.
let animal = Animal 5
// Get the Weight of the animal.
let weight = animal.Weight
printfn "%A" weight
Output
Animal created, size = 5
50
With get: We use the "with" keyword to introduce the get() accessor. This returns the value of the "color" mutable field.
And set: In F# we introduce a setter with "and set." The "and" is important. We store the argument "c" in the color field.
F# program that uses property, get, set
type Box() =
// A mutable color field.
let mutable color : string = null
// A Box has a color property with get and set.
member x.Color
with get() = color
and set(c) = color <- c
// Create a Box instance.
let x = Box()
// Set and get color values.
x.Color <- "blue"
printfn "%A" x.Color
// Set another value.
x.Color <- "red"
printfn "%A" x.Color
Output
"blue"
"red"
Here: We create a simple type called Color with one field. With typeof we get the System.Type.
F# program that uses typeof
// A type with one field.
type Color() =
let mutable Value = null
// Get typeof Color type.
// ... This is an instance of System.Type.
let t = typeof<Color>
printfn "%A" t
Output
Program+Color