Friday, April 13, 2012

Execution of Static Initializers

I have been struggling with the following code for days. Now it is clear that it is by design.

If you create a project with two files, one is File1.fs and the other is Program.fs. Put the following code in the File1.fs

namespace BB
// define a Point2D class with parameterized primary contructor
type Point2D(xValue:double, yValue:double) =
    // define a static field named count
    static let mutable count = 0
   
type Screen() =
    let points = System.Collections.Generic.List < Point2D > ()
    member this.Item with get(x:int) = points.[x]
                     and set(x:int) (v) = points.[x] <- v
module TestModule =
    let screen = Screen()
    let r2 = screen.[0]
and create the Point2D class in Program.fs.
let a = BB.Point2D()
When you run it you are going to bump into an exception about TypeInitializationException. OK, please move your staring eyes down to the TestModule, even it is 300 lines down below. screen.[0] is access a non-existing element. 


Do if a static variable is initialized, the module is also executed. So next time when you see this wired error, you  need to look around OR open the inner exception's call stack information. 


No comments: