Properties in F#

We’re talking class properties…

Automatic Properties

Let’s start with the one I seem to have most trouble remembering, especially as it’s a different syntax to the other properties. We’re talking automatic properties.

type Rectangle()= 
   member val length = 0 with get, set
   member val width = 0 with get, set

The key differences to the other property syntax, i.e. properties with backing fields (for example) are, the addition of the val keyword, the lack of a self-identifier, the initialization expression, i.e. the length = 0 and the get, set, i.e. no and.

So the above creates a type Rectangle and two auto properties, length and width. Both are initialized to 0.

Non-automatic properties

Let’s start with the syntax for a property with both a getter and setter. Let’s start with the version of the above automatic property example but with backing fields

Note: the use of this and value as the identifier and parameter respectively is just to use C# style naming and obviously can be changed to suit

type Rectangle() =
   let mutable l = 0
   let mutable w = 0
   member this.length 
      with get() = l
      and set value = l <- value
   member this.width
      with get() = w
      and set value = w <- value

The alternative syntax for the above is as follows

type Rectangle() =
   let mutable l = 0
   let mutable w = 0
   member this.length = l
   member this.length with set value = l <- value
   member this.width = w
   member this.width with set value = w <- value

Using properties

And just for completeness, let’s look at how we use properties on a class. As in C# we can simply use the following

let r = new Rectangle()
r.length <- 100

or using the F# equivalent of the C# initializer

let r = new Rectangle(length = 100)