views:

82

answers:

2

Given the following:

module MyModule =
    let myObj = new MyObj()

type MyType() =
    static let myObj_ = new MyObj()
    static member myObj = myObj_

... are MyModule.myObj and MyType.myObj functionally (no pun intended) equivalent?

Whenever I call MyModule.myObj or MyType.myObj, I don't want the code to actually create a new object. I just want access to methods on a singleton object. I'm hoping that either of the above are suitable to that purpose.

+4  A: 

Try it and see? I think these are the same, but I think you can author a MyObj type with a constructor that prints something and then easily verify the behavior with a short test program. (Or maybe you're asking about something else I'm unclear about.)

Brian
Good idea, Brian. I tried it, inserted a call to System.Windows.MessageBox.Show(string) in the () constructor. The message box did not appear when I assigned MyModule.myObj or MyType.myObj to a value; it came up only when the singletons were initialized, so it does indeed look like both methods are equivalent. Thanks for the suggestion!
MiloDC
+1  A: 

In both cases, the object is definitely only created once.

There is a small (theoretical) difference though. With the static let, the object is only guaranteed to be created before MyType is used the first time (MSDN).

A module-level let binding is probably executed at program startup (or maybe when a module is first used?).

wmeyer
Interesting. Good information, thanks wmeyer!
MiloDC