Thursday, September 20, 2012

Array.Create and mutable value

F#'s Array.Create take two parameters: one is the int and another is another a value. I got a customer report said the a0, a1, and a2 show the same value. He expected the value should be different.


type MyClass() =
    let mutable a = 3.0

    member this.A
        with get() = a
        and set(v) = a <- v

let b = Array.create 3 (MyClass())

b.[0].A < - 22.
b.[1].A < - 23.
b.[2].A < - 24.

let a0 = b.[0].A
let a1 = b.[1].A
let a2 = b.[2].A

The problem is the MyClass(), it create an instance of MyClass and the b array contains three references (pointers) to a single MyClass instance. I tried record type and it behaves the same.

No comments: