ZetCode

F# interfaces

last modified December 3, 2026

In this article we define and implement interfaces in F# and create objects with object expressions.

An interface is a named set of members without an implementation. A type that implements the interface provides all of them. Code written against the interface works with every type that implements it, whatever else the type does. Unlike a base class, an interface carries no data, and one type can implement many interfaces. Interfaces are common in .NET libraries, and F# code uses them to give unrelated types a shared set of operations.

Defining an interface

An interface is a type with only abstract members. A class implements it in an interface ... with section.

shape.fsx
type IShape =
    abstract Name: string
    abstract Area: float

type Circle(r: float) =
    interface IShape with
        member _.Name = "circle"
        member _.Area = System.Math.PI * r * r

let c = Circle(2.0)
let s = c :> IShape

printfn "%s with area %.2f" s.Name s.Area

The IShape interface has two properties, and the Circle class implements them. By .NET convention, interface names start with I.

let s = c :> IShape

The interface members are reached through a value of the interface type. The :> operator converts the circle to IShape; the conversion always succeeds, because the compiler checked that Circle implements the interface.

λ dotnet fsi shape.fsx
circle with area 12.57

Explicit implementation

F# implements interfaces explicitly: the members belong to the interface, not to the class. They cannot be called on a value of the class type.

explicit.fsx
type IShape =
    abstract Area: float

type Square(side: float) =
    interface IShape with
        member _.Area = side * side

let sq = Square(3.0)
printfn "%f" sq.Area

The script reads Area directly from the square.

printfn "%f" sq.Area

The compiler reports that Square has no member named Area. We either convert the value with :> first, or add a class member that forwards to the interface, for example member this.Area = (this :> IShape).Area.

λ dotnet fsi explicit.fsx
explicit.fsx(9,17): error FS0039: The type 'Square' does not define a field, constructor, or member named 'Area'.

Interfaces as parameter types

The main use of an interface is as the type of a parameter or of the elements of a collection. Any implementing type can then be passed in.

parameters.fsx
type IShape =
    abstract Name: string
    abstract Area: float

type Circle(r: float) =
    interface IShape with
        member _.Name = "circle"
        member _.Area = System.Math.PI * r * r

type Rectangle(w: float, h: float) =
    interface IShape with
        member _.Name = "rectangle"
        member _.Area = w * h

type Triangle(a: float, b: float, c: float) =
    interface IShape with
        member _.Name = "triangle"
        member _.Area =
            let s = (a + b + c) / 2.0
            sqrt (s * (s - a) * (s - b) * (s - c))

let describe (shape: IShape) =
    printfn "%-10s %6.2f" shape.Name shape.Area

describe (Circle(1.0))

let shapes: IShape list = [Circle(1.5); Rectangle(2.0, 3.5); Triangle(3.0, 4.0, 5.0)]

shapes |> List.iter describe

let largest = shapes |> List.maxBy (fun s -> s.Area)
printfn "largest: %s" largest.Name

Three unrelated classes implement IShape.

describe (Circle(1.0))

When a function parameter has an interface type, the compiler inserts the conversion itself, so no :> is needed.

let shapes: IShape list = [Circle(1.5); Rectangle(2.0, 3.5); Triangle(3.0, 4.0, 5.0)]

The annotation tells the compiler the element type, and each shape is converted to IShape. Without it, the list would take the type of its first element, and the compiler would reject the rectangle with error FS0193.

λ dotnet fsi parameters.fsx
circle       3.14
circle       7.07
rectangle    7.00
triangle     6.00
largest: circle

Methods in interfaces

Interface members can be methods with parameters. Their type is written as a function type; parameters separated by * become method parameters separated by commas.

logger.fsx
type ILogger =
    abstract Log: level: string * message: string -> unit

type ConsoleLogger() =
    interface ILogger with
        member _.Log(level, message) = printfn "[%s] %s" level message

type MemoryLogger() =
    let mutable lines = []
    member _.Lines = List.rev lines
    interface ILogger with
        member _.Log(level, message) = lines <- $"{level}: {message}" :: lines

let importFile (log: ILogger) (name: string) =
    log.Log("info", $"reading {name}")
    if name.EndsWith ".csv" then log.Log("info", "42 rows imported")
    else log.Log("error", $"unknown format: {name}")

importFile (ConsoleLogger()) "sales.csv"

let memory = MemoryLogger()
importFile memory "sales.csv"
importFile memory "notes.docx"

printfn "%d lines kept" memory.Lines.Length
for line in memory.Lines do
    printfn "  %s" line

The importFile function writes messages through a logger. It does not know whether they are printed or stored.

abstract Log: level: string * message: string -> unit

The parameter names are optional, but they document the method and appear in editor tooltips.

member _.Lines = List.rev lines

MemoryLogger has a member of its own besides the interface. memory has the class type, so Lines can be read directly, and the value is converted to ILogger when it is passed to importFile.

λ dotnet fsi logger.fsx
[info] reading sales.csv
[info] 42 rows imported
4 lines kept
  info: reading sales.csv
  info: 42 rows imported
  info: reading notes.docx
  error: unknown format: notes.docx

Object expressions

An object expression creates an object that implements an interface without declaring a class. It is written in braces with the new keyword.

object_expr.fsx
type IGreeter =
    abstract Greet: string -> string

let formal =
    { new IGreeter with
        member _.Greet name = $"Good morning, {name}." }

let casual =
    { new IGreeter with
        member _.Greet name = $"Hello there, {name}!" }

let greeters = [formal; casual]

for g in greeters do
    printfn "%s" (g.Greet "Tomas")

Two greeters are created without any class.

let formal =
    { new IGreeter with
        member _.Greet name = $"Good morning, {name}." }

The value of the expression has the type IGreeter, so no conversion is needed and the list needs no annotation. A method with a single parameter may be written without parentheses.

λ dotnet fsi object_expr.fsx
Good morning, Tomas.
Hello there, Tomas!

Object expressions with state

An object expression can use the values around it, like a lambda. A function that returns an object expression works as a small factory.

counter.fsx
type ICounter =
    abstract Next: unit -> int
    abstract Reset: unit -> unit

let makeCounter (start: int) (step: int) =
    let mutable current = start
    { new ICounter with
        member _.Next() =
            let value = current
            current <- current + step
            value
        member _.Reset() = current <- start }

let tickets = makeCounter 100 1
let evens = makeCounter 0 2

printfn "%d %d %d" (tickets.Next()) (tickets.Next()) (tickets.Next())
printfn "%d %d %d" (evens.Next()) (evens.Next()) (evens.Next())

tickets.Reset()
printfn "after reset: %d" (tickets.Next())

Each call to makeCounter creates a counter with its own current value.

let mutable current = start
{ new ICounter with
    member _.Next() =

The two members share the captured current variable. No code outside the object can reach it, as with a private field of a class.

λ dotnet fsi counter.fsx
100 101 102
0 2 4
after reset: 100

Interfaces on records and unions

Records and unions can implement interfaces too. The interface ... with section follows the fields of the record or the cases of the union.

records.fsx
type IPriced =
    abstract Price: decimal

type Book =
    { Title: string; Pages: int; Cost: decimal }
    interface IPriced with
        member this.Price = this.Cost

type Ticket =
    | Adult
    | Child
    | Family of members: int
    interface IPriced with
        member this.Price =
            match this with
            | Adult -> 12m
            | Child -> 6m
            | Family n -> 8m * decimal n

let basket: IPriced list =
    [ { Title = "Dune"; Pages = 412; Cost = 11.90m }
      Adult
      Family 4 ]

let total = basket |> List.sumBy (fun item -> item.Price)
printfn "total: %M" total

A book record and a ticket union both have a price.

member this.Price = this.Cost

Inside the implementation, this is the record or the union value. The types keep everything else: structural equality, copy and update expressions and pattern matching.

λ dotnet fsi records.fsx
total: 55.90

Several interfaces

A type can implement any number of interfaces. Each one gets its own interface ... with section.

several.fsx
type IShape =
    abstract Area: float

type IDrawable =
    abstract Draw: unit -> string

type Square(side: int) =
    interface IShape with
        member _.Area = float (side * side)

    interface IDrawable with
        member _.Draw() =
            let row = String.replicate side "#"
            String.concat "\n" (List.replicate side row)

let sq = Square(3)

printfn "area: %.1f" (sq :> IShape).Area
printfn "%s" ((sq :> IDrawable).Draw())

match box sq with
| :? IDrawable -> printfn "it can be drawn"
| _ -> printfn "it cannot be drawn"

The square has an area and can draw itself with characters.

match box sq with
| :? IDrawable -> printfn "it can be drawn"

A type test can ask whether an object implements an interface. This is how code checks for an optional capability; type tests are described in F# obj type.

λ dotnet fsi several.fsx
area: 9.0
###
###
###
it can be drawn

Interface inheritance

An interface can extend another one with inherit. A type that implements the extended interface must implement the members of both.

extending.fsx
type INamed =
    abstract Name: string

type IEmployee =
    inherit INamed
    abstract Salary: decimal

type Programmer(name: string, salary: decimal) =
    interface IEmployee with
        member _.Name = name
        member _.Salary = salary

let printName (x: INamed) = printfn "name: %s" x.Name

let p = Programmer("Lucia", 3400m) :> IEmployee

printName p
printfn "%s earns %M" p.Name p.Salary

IEmployee includes the Name member of INamed.

printName p

A value of IEmployee is also an INamed, so it can be passed to printName. The class implements both interfaces in a single section, because IEmployee includes INamed.

λ dotnet fsi extending.fsx
name: Lucia
Lucia earns 3400

Implementing IDisposable

.NET defines many interfaces that F# code implements. A type that holds a resource implements IDisposable, whose Dispose method releases it. A value bound with use is disposed at the end of its block; see F# exceptions.

disposable.fsx
type Connection(name: string) =
    do printfn "open %s" name

    member _.Send(text: string) = printfn "%s <- %s" name text

    interface System.IDisposable with
        member _.Dispose() = printfn "close %s" name

let sendReport () =
    use db = new Connection("db")
    use mail = new Connection("mail")
    db.Send "SELECT total FROM sales"
    mail.Send "report attached"
    printfn "report sent"

sendReport ()
printfn "done"

Two connections are opened and closed by use.

use db = new Connection("db")

The new keyword is recommended when creating a disposable object; without it, the compiler gives warning FS0760. The connections are closed in reverse order when the function ends, even if it raises an exception.

λ dotnet fsi disposable.fsx
open db
open mail
db <- SELECT total FROM sales
mail <- report attached
report sent
close mail
close db
done

Implementing IComparer

Some .NET methods take an interface instead of a function. An object expression is the shortest way to provide one. IComparer<'T> compares two values and is used, for example, by Array.Sort.

comparer.fsx
open System.Collections.Generic

let byLength =
    { new IComparer<string> with
        member _.Compare(a, b) =
            let c = compare a.Length b.Length
            if c <> 0 then c else compare a b }

let words = [| "plum"; "fig"; "banana"; "kiwi"; "apple"; "date" |]

System.Array.Sort(words, byLength)
printfn "%A" words

let sorted = SortedSet<string>(["pear"; "fig"; "cherry"; "lime"], byLength)
sorted.Add "melon" |> ignore
printfn "%A" (List.ofSeq sorted)

The comparer orders words by length and then alphabetically.

System.Array.Sort(words, byLength)

Array.Sort sorts the array in place. The same comparer keeps a SortedSet in order as words are added. In F# code Array.sortWith takes a comparison function instead; see F# sort.

λ dotnet fsi comparer.fsx
[|"fig"; "date"; "kiwi"; "plum"; "apple"; "banana"|]
["fig"; "lime"; "pear"; "melon"; "cherry"]

Report exporters

The last example writes the same data in several formats. Each format is an implementation of one interface, and a new format can be added without changing the code that uses them.

exporters.fsx
type Row = { City: string; Population: int }

type IExporter =
    abstract Name: string
    abstract Export: Row list -> string

type CsvExporter() =
    interface IExporter with
        member _.Name = "CSV"
        member _.Export rows =
            let lines = rows |> List.map (fun r -> $"{r.City},{r.Population}")
            String.concat "\n" ("city,population" :: lines)

type MarkdownExporter() =
    interface IExporter with
        member _.Name = "Markdown"
        member _.Export rows =
            let lines = rows |> List.map (fun r -> $"| {r.City,-10} | {r.Population,10} |")
            String.concat "\n" ("| City       | Population |" :: "|---|---|" :: lines)

let summary =
    { new IExporter with
        member _.Name = "summary"
        member _.Export rows =
            let total = rows |> List.sumBy (fun r -> r.Population)
            $"{rows.Length} cities, {total:N0} people" }

let rows =
    [ { City = "Bratislava"; Population = 475503 }
      { City = "Kosice"; Population = 229040 }
      { City = "Presov"; Population = 84824 } ]

let exporters: IExporter list = [CsvExporter(); MarkdownExporter(); summary]

for e in exporters do
    printfn "--- %s ---" e.Name
    printfn "%s" (e.Export rows)

Two exporters are classes and one is an object expression; the loop treats them alike.

abstract Export: Row list -> string

An interface member may take an F# type such as a list of records. The interface is the only thing the loop knows about an exporter.

let summary =
    { new IExporter with

A one-off implementation does not need a class. Object expressions suit small implementations that are used in one place.

λ dotnet fsi exporters.fsx
--- CSV ---
city,population
Bratislava,475503
Kosice,229040
Presov,84824
--- Markdown ---
| City       | Population |
|---|---|
| Bratislava |     475503 |
| Kosice     |     229040 |
| Presov     |      84824 |
--- summary ---
3 cities, 789,367 people

Source

F# language reference: Interfaces

F# language reference: Object expressions

In this article we have defined interfaces, implemented them in classes, records and unions, used them as parameter types, created objects with object expressions, extended an interface, and implemented the .NET interfaces IDisposable and IComparer. Base classes are covered in F# inheritance, and F# generics uses interfaces as type constraints.

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.