Home > Software engineering >  F# Object Tree Syntax
F# Object Tree Syntax

Time:12-12

In C# it is possible to construct object trees in a rather succint syntax:

var button = new Button() { Content = "Foo" };

Is there an idiomatic way to do something similar in F#?

Records have nice syntax:

let button = { Content = "Foo" }

Object construction would appear to be a different matter, as far as I can tell. Normally I would write code such as:

let button = new Button()
button.Content <- "Foo"

Or even:

let button =
    let x = new Button()
    x.Content <- "Foo"
    x

One way to solve the problem is to use a custom fluent composition operator:

// Helper that makes fluent-style possible
let inline (.&) (value : 'T) (init: 'T -> unit) : 'T =
    init value
    value

let button = new Button() .& (fun x -> x.Content <- "Foo")

Is there built-in syntax to achieve this - or another recommended approach?

CodePudding user response:

F# lets you set properties right in the constructor call, so I think this should work for you:

let button = Button(Content = "Foo")
  • Related