I’m just wondering if somebody can explain to me how to pass reference cells to functions that are not class members. I’ve been following the msdn page msdn reference cells
I have the following code:
let myint = ref 32
let mutable myint2 = 23
type addone() =
member t.myadd1func (x:int byref) =
x <- x + 1
let myadd1func (x:int byref) =
x <- x + 1
let adder = new addone()
adder.myadd1func myint
// myadd1func myint <---- this line does not compile
myadd1func &myint2 // <----- this line does though
printfn "%d" !myint
printfn "%d" myint2
My question is… what is the fundamental difference between the call I am making to the “Myadd1func” method on the class and the “myadd1func” function defined after it?
As I write this, I’m guessing that the function doesn’t like having .net object references being passed to it as this might break compatibility with other IL components?? I don’t mind using a mutable value, I just like to understand these things.
Thanks
This is explained in the Type-directed Conversions at Member Invocations section of the F# specification. For interoperability with other .NET components, ref cells can be passed to members taking
byrefparameters and the compiler will automatically treat it as the dereferencing of the cell’scontentsfield. However, this isn’t done for let-bound functions, and you should directly use the addressof operator (&). You can still use a ref cell, but you have to explicitly dereference thecontentsfield yourself, so this should work in your example:myadd1func &myint.contents