Unable to access Dispose method in F # class

I created a class in F # that implements the IDisposable interface. The class is cleared correctly, and the use keyword has access to the Dispose method. I have a second use case when I need to explicitly call the Dispose method and in the example below it fails. It looks like the Dipose method is not available in the class.

open System

type Foo() = class
    do
        ()

    interface IDisposable with
        member x.Dispose() =
            printfn "Disposing"

end

let test() =
    // This usage is ok, and correctly runs Dispose()
    use f = new Foo()


    let f2 = new Foo()
    // The Dispose method isn't available and this code is not valid
    // "The field , constructor or member Dispose is not defined."
    f2.Dispose()

test()
+5
source share
2 answers

An interface implementation in the F # class is more like an explicit interface implementation in C #, which means that interface methods do not become public method classes. To call them, you need to pass the class to the interface (which cannot fail).

This means that to call Disposeyou need to write:

(f2 :> IDisposable).Dispose()

, use , Dispose , , :

let test() =
  use f2 = new Foo()
  f2.DoSomething()

f2 , test.

+9

. FYI, Dispose() :

member x.Dispose() = (x :> IDisposable).Dispose()

IDisposable. f2.Dispose().

+1

All Articles