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