layout: post
title: “Object expressions”
description: “”
nav: fsharp-types
seriesId: “Object-oriented programming in F#”
seriesOrder: 5

categories: [Object-oriented, Interfaces]

So as we saw in the previous post, implementing interfaces in F# is a bit more awkward than in C#. But F# has a trick up its sleeve, called “object expressions”.

With object expressions, you can implement an interface on-the-fly, without having to create a class.

Implementing interfaces with object expressions

Object expressions are most commonly used to implement interfaces.
To do this, you use the syntax new MyInterface with ..., and the wrap the whole thing in curly braces (one of the few uses for them in F#!)

Here is some example code that creates a number of objects, each of which implements IDisposable.

  1. // create a new object that implements IDisposable
  2. let makeResource name =
  3. { new System.IDisposable
  4. with member this.Dispose() = printfn "%s disposed" name }
  5. let useAndDisposeResources =
  6. use r1 = makeResource "first resource"
  7. printfn "using first resource"
  8. for i in [1..3] do
  9. let resourceName = sprintf "\tinner resource %d" i
  10. use temp = makeResource resourceName
  11. printfn "\tdo something with %s" resourceName
  12. use r2 = makeResource "second resource"
  13. printfn "using second resource"
  14. printfn "done."

If you execute this code, you will see the output below. You can see that Dispose() is indeed being called when the objects go out of scope.

  1. using first resource
  2. do something with inner resource 1
  3. inner resource 1 disposed
  4. do something with inner resource 2
  5. inner resource 2 disposed
  6. do something with inner resource 3
  7. inner resource 3 disposed
  8. using second resource
  9. done.
  10. second resource disposed
  11. first resource disposed

We can take the same approach with the IAddingService and create one on the fly as well.

  1. let makeAdder id =
  2. { new IAddingService with
  3. member this.Add x y =
  4. printfn "Adder%i is adding" id
  5. let result = x + y
  6. printfn "%i + %i = %i" x y result
  7. result
  8. }
  9. let testAdders =
  10. for i in [1..3] do
  11. let adder = makeAdder i
  12. let result = adder.Add i i
  13. () //ignore result

Object expressions are extremely convenient, and can greatly reduce the number of classes you need to create if you are interacting with an interface heavy library.