Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module values in F# don't get initialized. Why?

Tags:

module

f#

I got a strange behavior when I used F#. When I use let binding in a module, and if the value is created from a constructor, then it's uninitialized when used outside. (I used it from C# using ModuleName.s2 or ModuleName.f())

//in a module
let s1 = "1" //normal
let s2 = new String('i', 5) //null

let f () =
    s2.Equals("something") //Exception

Is this a normal behavior? Thanks in advance.

EDIT: For the purpose of debugging, I choose to compile it as an executable. This may be the problem as other people pointed out.

like image 423
LLS Avatar asked Jul 08 '11 20:07

LLS


1 Answers

In an F# library, modules are initialized via static constructors which ensure that initialization occurs prior to any of the module's values being used. By contrast, in an F# executable, this initialization is performed in the application's entry point. This means that if another assembly references the F# application (regardless of the language the other application is written in), the initialization code won't be run.

UPDATE

Brian pointed me to this part of the spec, which indicates that this is the expected behavior.

It looks like one workaround would be to provide an explicit entry point, like this:

[<EntryPoint>]
let main _ =
    0

You can then call this main method from your C# app to ensure that the module's contents are properly initialized.

UPDATE 2

I was misreading the spec - you do not need to actually call the explicit entry point from the referencing assembly. Its mere presence will cause the initialization to occur correctly.

like image 133
kvb Avatar answered Sep 18 '22 17:09

kvb