Implementing a C# interface with an F# type
May 13, 2017 1 Comment
Suppose you have the following C# interface ICalculator with 4 functions:
namespace Project.Domains { public interface ICalculator { int Add(int x, int y); int Subtract(int x, int y); float Divide(float x, float y); int Multiply(int x, int y); } }
We can implement this interface in an F# type as follows:
module CSharpExamples open Project.Domains type FSharpCalculator() = interface ICalculator with member this.Add(x, y) = x + y member this.Subtract(x, y) = x - y member this.Divide(x, y) = x / y member this.Multiply(x, y) = x * y
Interfaces must be implemented explicitly in F#. We declare each implementing member with the ‘member’ keyword. If any of the interface functions are missing then we get a compile time error similar to the following:
No implementation was given for ‘ICalculator.Multiply(x: int, y: int) : int’. Note that all interface members must be implemented and listed under an appropriate ‘interface’ declaration, e.g. ‘interface … with member …’.
Using the FSharpCalculator class is a bit strange at first though. At least I expected the following code to work just fine:
let calcImpl = new CSharpExamples.FSharpCalculator() int res = calcImpl.Add(10, 20)
However, that results in an error:
The field, constructor or member ‘Add’ is not defined.
It turns out that we have to cast the implementation to the interface before we call its functions using the :> operator:
let calcImpl = new CSharpExamples.FSharpCalculator() let calcAbs = calcImpl :> ICalculator let sum = calcAbs.Add(10, 20);
Now it works as expected.
View all F# related articles here.
Pingback: F# Weekly #20, 2017 – Join FableConf in Bordeaux! – Sergey Tihon's Blog