Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call interface method on F# object from C#

Tags:

f#

c#-to-f#

Given an F# type:

type Foo() =
    member this.Prop with get() = ()

    interface IDisposable with
        member this.Dispose() = ()

In C#, I create the object, but I can't call Dispose():

var x = new Foo();
x.Dispose(); // compile error, x does not contain a definition of Dispose

However, I can write:

((IDisposable)x).Dispose(); // works, but I don't like the cast

Is there any way to avoid the cast in C#? Is this related to the way F# doesn't automatically let you call .Dispose() on the Foo type from within F#?

like image 702
Neil Mitchell Avatar asked Oct 17 '11 20:10

Neil Mitchell


2 Answers

Interface implementations in F# are explicit by default. Hence the methods are not visible unless seen from the type converted to the interface (some form of casting).

To work around this expose an instance method which has the same signature as the interface version. Then have the interface on forward to the instance function. For example

type Foo() =
    member this.Prop with get() = ()
    member this.Dispose() = ()

    interface IDisposable with
        member this.Dispose() = this.Dispose()
like image 200
JaredPar Avatar answered Nov 12 '22 23:11

JaredPar


How about, for this particular interface:

using (var x = new Foo()) {
    ...
}
like image 28
Daniel Avatar answered Nov 12 '22 23:11

Daniel