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.

[code language=”fsharp”]
let dispose() =
{ new System.IDisposable with
member x.Dispose() =
printfn "Disposed…" }
[/code]

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.

[code language=”fsharp”]
let callDispose() =
use d = dispose()
printfn "Calling dispose"
[/code]

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

[code language=”fsharp”]

callDispose();;
Calling dispose
Disposed…
[/code]

Now compare the above implementation to what you would have to do in C#.
[code language=”csharp”]
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…");
}
}
}[/code]
And, of course, running this we get the same results.

[code language=”fsharp”]
Calling dispose
Disposed…
[/code]


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#.