Saturday, March 2, 2013

Dispose pattern in F#

(In learning from "Programming F# 3.0, 2nd Edition")

If we want to access to unmanaged resources from C#,
  1. The class that indicates unmanaged resource should implement IDisposable interface and override Dispose method.
  2. When using this class, we should write the code with using () {} clause.

In F#, almost same.
  1. The class that indicates unmanaged resource should implement IDisposable interface and override Dispose method.
  2. When using this class, we should write the code with use binding.
> open System;;
> type SomeUnmanagedResource() =
-     interface IDisposable with
-         member this.Dispose() =
-             printfn "Some unmanaged resource is diposed.";;

type SomeUnmanagedResource =
  class
    interface IDisposable
    new : unit -> SomeUnmanagedResource
  end

> let greetings =
-     use res = new SomeUnmanagedResource()
-     printfn "Hello World";;
Hello World
Some unmanaged resource is diposed.

val greetings : unit = ()

No comments:

Post a Comment