Reputation: 968
I am used to member variables of an object keeping their value unless they are changed. So the following behviour in F# came as a bit of a surprise: (I have a class with 2 members, the second is supposedly initialized in the constructor by calling a gensym function)
let mutable gen_base = 0
let gensym prefix =
gen_base <- gen_base+1;
prefix + gen_base.ToString()
type C(m:int, s:string) =
member this.mm = m;
member this.x = gensym s
override this.ToString() = (this.mm.ToString()) + ", " + (this.x.ToString())
let testC =
let c = new C(1,"a")
printfn "c= %A" (c.ToString())
printfn "c again = %A" (c.ToString())
which prints the following:
c= "1, a1"
c again = "1, a2"
Why is the initializer for the member x called again simply because I inspect its value? What's the best way to keep it from doing that? Use an accessor function?
Upvotes: 3
Views: 140
Reputation: 131364
From the MSDN page on properties:
Note that the expression that initializes an automatically implemented property is only evaluated upon initialization, and not every time the property is accessed. This behavior is in contrast to the behavior of an explicitly implemented property.
this.x
is explicitly initialized which means it will be evaluated every time you access it.
To turn it into an automatically initialized property, you will have to change it to this:
member val x = gensym s
Upvotes: 4