Static constructors in F # - when do they start?

I am experimenting with various ways to create singleton in F # to better understand the subtleties. I don't know if a singleton template is useful in F #, but I wanted to experiment. And I was surprised at one result involving static constructors on these singleton instances. First, I will show you my code, and then I will tell you more about my question.

In one project called TrySingletonI created three modules. Here Eager.fs:

module TrySingleton.Eager

type EagerClass() =
    do
        printfn "Initializing eager class..."

    static do
        printfn "Static constructor of eager class"

let Instance = EagerClass()

Here Lazy.fs:

module TrySingleton.Lazy

type LazyClass() =
    do
        printfn "Initializing lazy class..."

    static do
        printfn "Static constructor of lazy class"

let Instance = lazy LazyClass()

And here is what I call them in Main.fs:

module TrySingleton.Main

[<EntryPoint>]
let main argv =
    printfn "Starting main with args %A" argv
    printfn "Accessing eager instance:"
    printfn "%A" Eager.Instance
    printfn "Accessing lazy instance:"
    printfn "%A" Lazy.Instance.Value
    printfn "Accessing eager instance again:"
    printfn "%A" Eager.Instance
    printfn "Accessing lazy instance again:"
    printfn "%A" Lazy.Instance.Value
    printfn "Success; exiting."
    0

I expected that the static constructor of the class Eagerwould start immediately when the program started and was not sure when the static constructor of the class would start Lazy. However, here I got the result:

Starting main with args [||]
Accessing eager instance:
Static constructor of eager class
Initializing eager class...
TrySingleton.Eager+EagerClass
Accessing lazy instance:
Static constructor of lazy class
Initializing lazy class...
TrySingleton.Lazy+LazyClass
Accessing eager instance again:
TrySingleton.Eager+EagerClass
Accessing lazy instance again:
TrySingleton.Lazy+LazyClass
Success; exiting.

, Eager , . , , , .

, , : - ? , , ?

+4
1

F #, , http://fsharpforfunandprofit.com - . F # ( ):

let do , , , .

let do , ( ):

Static let , , .

A do do, , .

, , : , . , . , Singleton , , ( ) , . (, , , , .)

+6

Source: https://habr.com/ru/post/1653859/


All Articles