Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Object constructor

After recently picking up a bit of C# after a long time of F#, I came to realise that 'object constructors' are a nice way of tricking oneself into believing they are dealing with a functional object.

Consider:

let x = new Something()
x.Key <- 1
x.Value <- 2

This feels very unclean because of the very obvious mutation of values. Especially if we keep our objects write once, it feels very unnecessary In C#, it is possible to initialise the object like this:

var x = new Something() { Key = 1, Value = 2 };

This looks nicer and actually it felt like I was using a record (almost), obviously its just sugar but its nice sugar.

Q. Assuming we have no control over `Something' (pretend its from some C# library), is it possible, in F# to use this shorthand initialisation, if not, why?


1 Answers

Yes, you can do that. It would look something like this:

let x = new Something(Key = 1, Value = 2)

The syntax is detailed in Constructors (F#) under the section "Assigning Values to Properties at Initialization".

like image 103
p.s.w.g Avatar answered Apr 02 '26 05:04

p.s.w.g