In F #, how do I initialize static fields in a type without a main constructor?

I have an F # class that comes from a .net class with several constructors. To expose them all, I implement a type without a main constructor. Now I would like to add a static field. How to initialize a 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 this type is used, and not at all if this type is never used? Essentially, I need the equivalent of a block of static C # constructors.

+7
f # c # -to-f #
source share
1 answer

See F # spec , section 8.6.3 Additional object constructors in classes:

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

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 
+2
source share

All Articles