Search code examples
f#dispose

Can't access Dispose method in F# class


I have created a class in F# that implements the IDisposable interface. The class is cleaned up correctly and the use keyword is able to access the Dispose method. I have a second use case where I need to explicitly call the Dispose method and am unable to in the example below. It appears as though the Dipose method isn't 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()

Solution

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

    This means that, to call Dispose you need to write:

    (f2 :> IDisposable).Dispose()
    

    In practice, this is not needed very often, because the use keyword ensures that Dispose is called automatically when the value goes out of scope, so I would write:

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

    Here, f2 gets disposed when the test function returns.