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.
Answer: 50° Celsius is equal to 122° Fahrenheit.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With