Monday, March 19, 2012

F# 3.0 Automatically Implemented Property

F# 3.0 implements a new feature: Automatically Implemented Property (AIP). This simplifies the property declaration in a type definition, but there are more than that.

The basic AIP is you can define a property with a more concise syntax, the MyProperty below is a AIP.
type MyType() = class
    member val MyProperty = 0 with get, set
The property MyProperty will be translated to something like the following:
type MyClass() = class
    val mutable internal MyProperty@ : int
    member this.MyProperty with get() = this.MyProperty@
                                           and set(v) = this.MyProperty@ < - v
From the definition, you will see the there is a back-end field "MyProperty@". As a result, MyProperty@ shows in the class definition when debug the program.

The interesting part for this definition is the 0 in the definition. It is the initial value for the back-end property. If you like to reference to a value outside of the class definition, you can write something like.
let mutable a = 10
type MyType() = class
    member val MyProperty = a with get, set
the value from "a" will be taken as initial value for MyProperty. It does not mean MyProperty is a wrapper for "a".

you can make "a" immutable and the code still compile and work.

There are two important notes I have to put with AIP:
  • the back-end field "MyProperty@" does not decorate with "CompilerGenerateAttribute"
  • the object expression does not support AIP.
  • the property's getter and setter always have the accessibility modifier, which is either public or private. You cannot do something like member val MyProperty = 0 with get, private set.
  • Also, you do not put any attribute on the get and set.

No comments: