Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In F#, how do I initialize static fields in a type with no primary constructor?

Tags:

f#

c#-to-f#

I have an F# class that derives from a .net class with multiple constructors. To expose them all, I implement a type with no primary constructor. Now I would like to add a static field. How do I initialize the static field? Consider this:

type MyType =
    inherit DotNetType
    [<DefaultValue>] static val mutable private myStatic : int
    new () = { inherit DotNetType() }
    new (someArg:string) = { inherit DotNetType(someArg) }

Now, how do I initialize the "myStatic" field in a way that runs exactly once if the type is used, and not at all if the type is never used? Essentially, I need the equivalent of a C# static constructor block.

like image 969
Bruno Bozza Avatar asked Sep 06 '15 03:09

Bruno Bozza


People also ask

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.


2 Answers

I had same wondering as the OP and I didn't like the only accepted answer. In my case what I ended up doing is just use a normal field (via let) inside a module element, instead of a type one.

like image 81
knocte Avatar answered Jan 04 '23 05:01

knocte


See the F# spec, section 8.6.3 Additional Object Constructors in Classes:

For classes without a primary constructor, side effects can be performed after the initialization of the fields of the object by using the additional-constr-expr then stmt form.

Example:

type MyType  =
    inherit DotNetType
    [<DefaultValue>] static val mutable private myStatic : int
    new () = { inherit DotNetType() } then MyType.myStatic <- 1
    new (someArg:string) = { inherit DotNetType(someArg) }
    static member Peek = MyType.myStatic

MyType.Peek |> printfn "%d" // prints 0
MyType() |> ignore
MyType.Peek |> printfn "%d" // prints 1
like image 36
kaefer Avatar answered Jan 04 '23 06:01

kaefer