Implementing Interfaces in F# Using Object Expressions

To expand on another topic that was mentioned in the F# Infographic is that F# also has the ability to use any .NET library. From that, you may be wondering, “what about implementing interfaces that may come in other libraries?” Of course, you can create classes in F# if you need but there’s a more elegant solution – object expressions.

Let’s take a look and implement one of the most use interfaces in .NET – IDisposable.

let dispose() =
 { new System.IDisposable with
 member x.Dispose() =
 printfn "Disposed..." }

As you may tell, we’re declaring a function dispose and implementing the IDisposable interface on it. Now let’s make use of this method.

let callDispose() =
 use d = dispose()
 printfn "Calling dispose"

And now we can just call the above in the F# interactive and we get the following results:

</pre>
<blockquote>callDispose();; Calling dispose Disposed... 

Now compare the above implementation to what you would have to do in C#.

using System;

namespace ConsoleApplication1
{
 class Program
 {
     static void Main(string[] args)
     {
        using (var d = new DisposableClass())
         {
         Console.WriteLine("Calling dispose");
         }
      }
  }

class DisposableClass : IDisposable
 {
     public void Dispose()
     {
         Console.WriteLine("Disposed...");
     }
 }
}

And, of course, running this we get the same results.

Calling dispose
Disposed...

From the above comparison of the same F# and C# code, object expressions are definitely a more elegant way to implement interfaces in your F# code. If the interface was much bigger, then the C# class can get pretty big as opposed to the F# code you’d have to do. I wouldn’t be surprised if this feature may be implemented in a future version of C#.

Jonathan Wood

View Comments

Recent Posts

How to Navigate Azure Governance

 Cloud management is difficult to do manually, especially if you work with multiple cloud…

6 days ago

Why Azure’s Scalability is Your Key to Business Growth & Efficiency

Azure’s scalable infrastructure is often cited as one of the primary reasons why it's the…

3 weeks ago

Unlocking the Power of AI in your Software Development Life Cycle (SDLC)

https://www.youtube.com/watch?v=wDzCN0d8SeA Watch our "Unlocking the Power of AI in your Software Development Life Cycle (SDLC)"…

1 month ago

The Role of FinOps in Accelerating Business Innovation

FinOps is a strategic approach to managing cloud costs. It combines financial management best practices…

1 month ago

Azure Kubernetes Security Best Practices

Using Kubernetes with Azure combines the power of Kubernetes container orchestration and the cloud capabilities…

2 months ago

Mastering Compliance: The Definitive Guide to Managed Compliance Services

In the intricate landscape of modern business, compliance is both a cornerstone of operational integrity…

2 months ago