John Reynolds
John Reynolds

Reputation: 5057

How to make a local constructor variable into a member

I create a timer in a constructor and want to make the timer a member of the constructed class. Since the timer isn't referenced by any other class member, it's compiled into a variable that is local to the constructor and hence garbage collected and killed.

One way of preventing this from happening is to make a dummy reference, like

type MyClass() as o =
    let timer = new Timer((fun _ -> o.Tick()), null, 0, 1000)

    member private o.DummyRef = timer
    member o.Tick() = printfn "Tick!"

Is there a neater way of forcing timer into becoming a member?

Upvotes: 0

Views: 151

Answers (2)

Daniel
Daniel

Reputation: 47914

If you want it to be a member then let is the wrong tool for the job, since, according to the spec, the compiled form (local variable or field) is determined by the compiler. You probably want a private property:

type MyClass() as o =
    member val private Timer = new Timer((fun _ -> o.Tick()), null, 0, 1000)

Upvotes: 5

Leaf Garland
Leaf Garland

Reputation: 3697

Because you don't use timer anywhere, it is being optimized to a constructor local. If you were to use it somewhere else in your type definition then it would be compiled as a field of the class. e.g.

type MyClass() as o =
    let timer = new Timer((fun _ -> o.Tick()), null, 0, 1000)

    member o.Tick() = printfn "Tick"

    interface IDisposable with
        member x.Dispose() = timer.Dispose()

Upvotes: 1

Related Questions