liveBook · Manning

Constructor method

As explained in F# in Action: A Revised Edition of Get Programming with F#

A constructor is a member or function-like operation that creates and initializes an instance of a type.

A constructor creates an instance and initializes its values. In F#, a class constructor is declared alongside the type and its parameters are available to the class members. section 15.2.1

F# also lets you use a class constructor like a function: passing an argument to FileInfo returns a FileInfo object. The concise form is idiomatic F#; the explicit new form remains valid. section 11.1.1

Constructing a .NET object

open System.IO let fileInfo = FileInfo __SOURCE_FILE__ let explicitFileInfo = new FileInfo(__SOURCE_FILE__) Both expressions construct a FileInfo value. The first emphasizes the constructor's function-like use; the second makes object construction explicit. section 11.1.1

Constructing a C# class from F#

open CsCode let person = Person () printfn $"{person.Name} is {person.Age} years old!" The Person constructor initializes Name to Tamara and Age to 21, after which F# accesses the initialized properties. section 11.1.1

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains declaration, implicit member access, and concise versus explicit invocation, but does not detail compiler internals.
Examples
Uses FileInfo, a C# Person class, and an ATM class receiving a Customer through its constructor.
What you can do after
Apply it via F# syntax to construct .NET objects and instances of classes defined in C# or F#.
How it connects
Connects constructors with classes, objects, .NET interoperability, interfaces, and object-oriented composition.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.