ZetCode

F# classes

last modified December 2, 2026

In this article we define classes in F#.

A class is a type that bundles data with the functions that work on it, called members. Values of a class are objects. F# code usually models data with records and unions and keeps functions in modules; classes are used when an object has to hide and manage its own state, and when F# code works with .NET libraries, which are built from classes.

A simple class

A class is declared with type, a name and a parameter list called the primary constructor. Its members are defined with the member keyword.

point.fsx
type Point(x: float, y: float) =
    member _.X = x
    member _.Y = y

let p = Point(3.0, 4.0)

printfn "x = %.1f, y = %.1f" p.X p.Y

The Point class takes two numbers when an object is created.

member _.X = x

X is a read-only property that returns the constructor parameter x. The underscore before the dot stands for the object itself, which this member does not need.

let p = Point(3.0, 4.0)

An object is created by calling the class name like a function, with the arguments in parentheses.

λ dotnet fsi point.fsx
x = 3.0, y = 4.0

Methods

A member with parameters is a method. To refer to the object itself, the member declares a name before the dot, usually this.

methods.fsx
type Point(x: float, y: float) =
    member _.X = x
    member _.Y = y

    member this.DistanceTo(other: Point) =
        let dx = this.X - other.X
        let dy = this.Y - other.Y
        sqrt (dx * dx + dy * dy)

    member _.Move(dx, dy) = Point(x + dx, y + dy)

    member _.Describe() = $"({x}, {y})"

let a = Point(0.0, 0.0)
let b = Point(3.0, 4.0)
let c = b.Move(1.0, -2.0)

printfn "%s to %s: %.2f" (a.Describe()) (b.Describe()) (a.DistanceTo b)
printfn "%s" (c.Describe())
printfn "%.2f" (c.DistanceTo(a))

We add three methods to Point.

member this.DistanceTo(other: Point) =

this is the object the method is called on. The parameter type is needed, because the compiler cannot infer the type of other from the property access alone.

member _.Move(dx, dy) = Point(x + dx, y + dy)

Move does not change the point; it returns a new one. Method parameters are written in parentheses and separated with commas, as in other .NET languages.

member _.Describe() = $"({x}, {y})"

A method without parameters takes (). Without it, Describe would be a property.

λ dotnet fsi methods.fsx
(0, 0) to (3, 4): 5.00
(4, 2)
4.47

Constructor code

let bindings and do blocks before the members run when an object is created. The let values are private fields: the members can use them, but code outside the class cannot.

constructor.fsx
type Rectangle(width: float, height: float) =
    do
        if width <= 0.0 || height <= 0.0 then
            invalidArg "size" "width and height must be positive"

    let area = width * height
    let isSquare = width = height

    do printfn "created %gx%g" width height

    member _.Area = area
    member _.IsSquare = isSquare
    member _.Scale(factor) = Rectangle(width * factor, height * factor)

let r = Rectangle(4.0, 2.5)
printfn "area %g, square %b" r.Area r.IsSquare

let s = Rectangle(3.0, 3.0).Scale(2.0)
printfn "area %g, square %b" s.Area s.IsSquare

try
    Rectangle(-1.0, 5.0) |> ignore
with
| :? System.ArgumentException as e -> printfn "error: %s" e.Message

The Rectangle class validates its arguments and computes its area once, when it is created.

do
    if width <= 0.0 || height <= 0.0 then
        invalidArg "size" "width and height must be positive"

The first do block checks the arguments. An invalid rectangle is never created, because the constructor raises an exception; see F# exceptions.

let area = width * height
let isSquare = width = height

These values are computed once per object. The second line binds the result of the comparison width = height.

λ dotnet fsi constructor.fsx
created 4x2.5
area 10, square false
created 3x3
created 6x6
area 36, square true
error: width and height must be positive (Parameter 'size')

Mutable state and properties

A class can keep mutable state in a let mutable field. Only its members can change it, so the class controls every change. A property with a getter and a setter is declared with with get and and set.

account.fsx
type Account(owner: string) =
    let mutable balance = 0m
    let mutable limit = 400m

    member _.Owner = owner
    member _.Balance = balance

    member _.Limit
        with get () = limit
        and set value =
            if value < 0m then invalidArg "value" "limit cannot be negative"
            limit <- value

    member _.Deposit(amount) =
        if amount <= 0m then invalidArg "amount" "must be positive"
        balance <- balance + amount

    member _.Withdraw(amount) =
        if amount > balance || amount > limit then false
        else
            balance <- balance - amount
            true

let acc = Account("Lucia")
acc.Deposit 300m
acc.Deposit 350m
printfn "%s has %M" acc.Owner acc.Balance

printfn "withdraw 500: %b" (acc.Withdraw 500m)
printfn "withdraw 200: %b" (acc.Withdraw 200m)
printfn "balance %M" acc.Balance

acc.Limit <- 2500m
printfn "limit %M" acc.Limit

The account balance can only change through Deposit and Withdraw. A withdrawal fails when it exceeds the balance or the limit; the first one asks for more than the limit of 400.

member _.Balance = balance

Balance is a read-only property. It reads the field each time it is accessed, so it always returns the current value.

member _.Limit
    with get () = limit
    and set value =
        if value < 0m then invalidArg "value" "limit cannot be negative"
        limit <- value

Limit is the largest amount that can be withdrawn at once; it can be read and written. The setter is assigned with <-, like a mutable variable, and it checks the new value before it stores it.

λ dotnet fsi account.fsx
Lucia has 650
withdraw 500: false
withdraw 200: true
balance 450
limit 2500

Auto-properties

A property that only stores a value needs no explicit field. member val declares an auto-property: the compiler creates the field, and with get, set makes the property writable.

auto_properties.fsx
type TodoItem(title: string) =
    member val Title = title with get, set
    member val Done = false with get, set
    member val Priority = 2 with get, set
    member val Created = System.DateOnly(2026, 12, 2)

let t = TodoItem("write report")
printfn "%s, done %b, priority %d" t.Title t.Done t.Priority

t.Done <- true
t.Title <- "write the annual report"
printfn "%s, done %b, created %s" t.Title t.Done (t.Created.ToString "yyyy-MM-dd")

let urgent = TodoItem("fix the server", Priority = 1)
printfn "%s, priority %d" urgent.Title urgent.Priority

The TodoItem class has four auto-properties.

member val Done = false with get, set

The initial value is computed once, when the object is created. Without with get, set, as for Created, the property is read-only.

let urgent = TodoItem("fix the server", Priority = 1)

Writable properties can be set right in the constructor call, after the constructor arguments. This is called a property setter in the call.

λ dotnet fsi auto_properties.fsx
write report, done false, priority 2
write the annual report, done true, created 2026-12-02
fix the server, priority 1

Additional constructors

A class can have more ways to create an object. Additional constructors are defined with new, and each must call the primary constructor.

constructors.fsx
type Color(r: int, g: int, b: int) =
    new(gray: int) = Color(gray, gray, gray)
    new() = Color(0, 0, 0)

    member _.R = r
    member _.G = g
    member _.B = b
    member _.Hex = $"#%02X{r}%02X{g}%02X{b}"

let orange = Color(255, 165, 0)
let gray = Color(128)
let black = Color()

for c in [orange; gray; black] do
    printfn "%3d %3d %3d %s" c.R c.G c.B c.Hex

A colour is created from three components, from one gray level, or with no arguments as black.

new(gray: int) = Color(gray, gray, gray)

The constructor with one parameter calls the primary constructor with the same value three times. Constructors are told apart by the number and types of their parameters.

member _.Hex = $"#%02X{r}%02X{g}%02X{b}"

An interpolated string can contain format specifiers before the braces; %02X prints a two-digit hexadecimal number.

λ dotnet fsi constructors.fsx
255 165   0 #FFA500
128 128 128 #808080
  0   0   0 #000000

Static members

Static members belong to the class, not to its objects. They are called on the class name. A static let field is shared by all objects.

static_members.fsx
type Ticket(event: string) =
    static let mutable issued = 0

    let number =
        issued <- issued + 1
        issued

    member _.Event = event
    member _.Number = number
    member _.Code = Ticket.MakeCode(event, number)

    static member Issued = issued

    static member MakeCode(event: string, n: int) =
        $"{event.ToUpper()[0..2]}-{n:D4}"

let tickets = [Ticket("concert"); Ticket("concert"); Ticket("opera")]

for t in tickets do
    printfn "%d %s %s" t.Number t.Event t.Code

printfn "issued: %d" Ticket.Issued
printfn "%s" (Ticket.MakeCode("ballet", 42))

Each ticket gets the next number from a counter shared by the class.

static let mutable issued = 0

let number =
    issued <- issued + 1
    issued

There is one issued field for the whole class. Each new object increases it and keeps the result in its own number field.

static member MakeCode(event: string, n: int) =
    $"{event.ToUpper()[0..2]}-{n:D4}"

A static method needs no object, so it can be called from outside as Ticket.MakeCode and from the members as well. The code is made of the first three letters of the event and the number padded to four digits. .NET methods such as Math.Sqrt and Int32.Parse are static members too.

λ dotnet fsi static_members.fsx
1 concert CON-0001
2 concert CON-0002
3 opera OPE-0003
issued: 3
BAL-0042

Optional parameters

Method parameters can be optional. An optional parameter has a question mark before its name, and inside the method its value is an option.

optional.fsx
type Formatter() =
    member _.Format(value: float, ?decimals: int, ?unit: string) =
        let d = defaultArg decimals 2
        let u = defaultArg unit ""
        value.ToString($"F{d}") + u

let f = Formatter()

printfn "%s" (f.Format 3.14159)
printfn "%s" (f.Format(3.14159, 4))
printfn "%s" (f.Format(21.5, unit = " °C"))
printfn "%s" (f.Format(1234.5678, decimals = 0, unit = " m"))

The Format method has one required and two optional parameters.

let d = defaultArg decimals 2

decimals has the type int option. The defaultArg function returns the value of Some, or the default when the argument was omitted.

printfn "%s" (f.Format(21.5, unit = " °C"))

Named arguments allow us to skip decimals and give only the unit. Optional parameters are only available in methods, not in let-bound functions.

λ dotnet fsi optional.fsx
3.14
3.1416
21.50 °C
1235 m

Classes and records

Records and classes differ in equality. Records are equal when their fields are equal; two objects of a class are equal only when they are the same object.

equality.fsx
type PointRecord = { X: int; Y: int }

type PointClass(x: int, y: int) =
    member _.X = x
    member _.Y = y

let r1 = { X = 1; Y = 2 }
let r2 = { X = 1; Y = 2 }

let c1 = PointClass(1, 2)
let c2 = PointClass(1, 2)
let c3 = c1

printfn "records equal: %b" (r1 = r2)
printfn "objects equal: %b" (c1 = c2)
printfn "same object: %b" (c1 = c3)
printfn "%A" r1
printfn "%s" (c1.GetType().Name)

Two points with the same coordinates are compared, once as records and once as objects.

printfn "objects equal: %b" (c1 = c2)
printfn "same object: %b" (c1 = c3)

c1 and c2 hold equal data, but they are two objects, so they are not equal. c3 refers to the same object as c1; see F# copy by value and reference. Records also print their fields with %A, while objects print only their type unless they define a text form. Records suit plain data; classes suit objects with behaviour and hidden state.

λ dotnet fsi equality.fsx
records equal: true
objects equal: false
same object: true
{ X = 1
  Y = 2 }
PointClass

Source

F# language reference: Classes

F# language reference: Members

In this article we have defined classes with primary constructors, methods and properties, kept private and mutable state, used auto-properties, additional constructors and static members, and compared classes with records. Records are covered in F# records, modules in F# modules and namespaces, and exceptions in F# exceptions.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.