Object expressions
Last updated
Was this helpful?
Last updated
Was this helpful?
So as we saw in the , 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.
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
.
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.
We can take the same approach with the IAddingService
and create one on the fly as well.
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.