Thursday, September 27, 2012

Learning F# 3.0 : auto-property

Fundamentally, any instances on F# should be immutable. But, if we use F# as C# substitute, we might want mutable object like POCO/POJO. Until F# 2.0, we writed like that:
type Person2() =
    let mutable firstName:string = ""
    let mutable lastName:string = ""
    let mutable age:int = 0
    member this.FirstName with get() = firstName
                          and set(n) = firstName <- n
    member this.LastName with get() = lastName
                         and set(n) = lastName <- n
    member this.Age with get() = age
                    and set(n) = age <- n
But, this is a little complicated. So that, since F# 3.0, here comes the syntax sugar called auto-property:
type Person3() =
    member val FirstName:string = "" with get, set
    member val LastName:string = "" with get, set
    member val Age:int = 0 with get, set
It looks like "Plain Old F# Object"!

No comments:

Post a Comment