Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Types, Records and Unions

Classes, Interfaces and Object Expressions

Learn object-oriented F#: classes with primary constructors, members, mutable state, interfaces, abstract classes, inheritance and object expressions, and when to prefer functions and records.

F# is a functional-first language, not a functional-only one. It sits on .NET, where classes and interfaces are everywhere, so F# has full support for them. You will use classes when you need hidden mutable state, when you implement a .NET interface, or when you design a library for C# callers. This lesson shows the F# way to write them, which is shorter than most people expect.

A class with a primary constructor

FSHARP
type Counter(start: int) =
    let mutable count = start

    member this.Value = count
    member this.Increment() = count <- count + 1
    member this.Add(n: int) = count <- count + n

let c = Counter(10)
c.Increment()
c.Add 5
printfn "%d" c.Value     // 16

The parameter list after the type name is the primary constructor. let bindings inside the class are private fields; let mutable makes one changeable with <-. member declares public members: Value is a property (no parentheses), while Increment() is a method. The word before the dot (this) is just a name for the current instance, and you can choose another or use _ when it is unused.

To run code at construction time use a do binding:

FSHARP
type Logger(name: string) =
    do printfn "creating logger %s" name
    member _.Log msg = printfn "[%s] %s" name msg

You do not need new to create an object; if the type is IDisposable the compiler prefers new as a hint to dispose it (use use bindings).

C# C# stand-in: the same Counter class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Properties with get and set

Auto-properties and explicit properties look like this:

FSHARP
type Temperature() =
    member val Celsius = 0.0 with get, set
    member this.Fahrenheit
        with get () = this.Celsius * 9.0 / 5.0 + 32.0
        and set (f: float) = this.Celsius <- (f - 32.0) * 5.0 / 9.0

let t = Temperature(Celsius = 100.0)    // property setter in the call
printfn "%.1f" t.Fahrenheit             // 212.0

member val creates an auto-property that is initialised once. Passing Celsius = 100.0 while constructing sets a settable property, a convenient shorthand borrowed from .NET object initialisers.

Interfaces

An interface lists members without bodies. Declare one with only abstract members and implement it with interface ... with:

FSHARP
type IShape =
    abstract Area: float
    abstract Describe: unit -> string

type Square(side: float) =
    interface IShape with
        member _.Area = side * side
        member this.Describe() = $"square of side {side}"

let s = Square(3.0) :> IShape       // upcast to the interface
printfn "%s, area %.1f" (s.Describe()) s.Area

F# implements interfaces explicitly: the members are reachable only through the interface type, which is why the value is upcast with :>. This is a common surprise for C# programmers. Often you can avoid an interface entirely by passing a function (float -> string) or a record of functions, which is lighter.

Abstract classes and inheritance

FSHARP
[<AbstractClass>]
type Animal(name: string) =
    member _.Name = name
    abstract Sound: string
    default this.Sound = "..."          // optional default

type Dog(name: string) =
    inherit Animal(name)
    override _.Sound = "Woof"

type Fish(name: string) =
    inherit Animal(name)

let animals : Animal list = [ Dog "Rex"; Fish "Nemo" ]
for a in animals do
    printfn "%s says %s" a.Name a.Sound

abstract plus default makes a virtual member with an implementation; override replaces it. Mark a class [<AbstractClass>] when it has abstract members without defaults. F# supports single inheritance only, like the rest of .NET. Prefer composition and small interfaces over deep hierarchies.

Object expressions

Sometimes you need an object that implements an interface once, without naming a class. An object expression creates one on the spot:

FSHARP
let makeGreeter (greeting: string) =
    { new IShape with
        member _.Area = 0.0
        member _.Describe() = greeting }

let g = makeGreeter "hello"
printfn "%s" (g.Describe())

Object expressions can also inherit a class and override members. They are perfect for test doubles and one-off callbacks, and they close over local values naturally, as greeting is captured above.

C# C# stand-in: interface plus an anonymous-style implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When to use what

flowchart TD
    A["Need to model something"] --> B{"Just data?"}
    B -->|yes| C["Record or union"]
    B -->|no| D{"Hidden mutable state<br/>or .NET interface?"}
    D -->|no| E["Functions in a module"]
    D -->|yes| F["Class"]
    F --> G{"Several implementations?"}
    G -->|yes| H["Interface + object expressions"]

Start with records and functions; reach for classes when the problem demands them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the parameters after the type name in type Counter(start: int)?

    The primary constructor's parameters are available throughout the class body.
  2. 2. How do you call an interface member on a class that implements it with interface ... with?

    F# implements interfaces explicitly, so members are visible only through the interface type.
  3. 3. What is an object expression?

    { new IShape with ... } builds an anonymous implementation in place.
  4. 4. Which keyword replaces an abstract member's implementation in a derived class?

    override replaces a virtual member; default supplies the base implementation next to abstract.

Summary

  • Classes use a primary constructor, private let fields and public members.
  • let mutable and <- give controlled mutable state; member val makes auto-properties.
  • Interfaces are implemented explicitly with interface ... with; upcast with :>.
  • Abstract classes use abstract, default and override; inheritance is single.
  • Object expressions create anonymous implementations; often a plain function is even simpler.

Next: Pattern Matching in Depth