Now that you understand the basics about what an object is, you can begin creating custom types of your own. Classes on the simplest level are functions glued to data. Data associated with a class are known as fields. Functions associated with a class are known as properties or members. (Properties are simply parameter-less methods.)
I’ll cover each aspect of fields, methods, and properties in time. But creating a new class isn’t going to be useful unless you can initialize it with some initial state. Classes have special methods called constructors, whose job is to initialize the class’s fields.
A class’s constructor is called when it is created by a call to
new, and it may not be invoked again
once the class has been instantiated.
F# features two separate syntaxes for defining class constructors: explicit constructors and implicit constructors. One is in line with F#’s simple yet terse syntax, while the other allows for more explicit control over how the class is generated.
The explicit class construction syntax is the least pleasant way to construct a class, but it provides the greatest degree of control. When you define a class using this syntax, you must explicitly name each class field and initialize each field with a constructor.
Class fields are prefixed with the
val keyword and are
accessed by using the self identifier, discussed later.
Example 5-3 defines a new
Point, which has two
m_y. The class has two ...