F # Object Constructor

After I put together a little C # after a long time, F #, I realized that “object constructors” are a good way to fool themselves into believing that they are dealing with a functional object.

Consider:

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

It seems very unclean due to a very obvious mutation of values. Especially if we store our objects once, it seems very unnecessary. In C #, you can initialize an object as follows:

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

It looks better, and in fact it seemed to me that I used the record (almost), obviously its just sugar, but its good sugar.

Q. Assuming we don’t have control over “Something” (pretending to be from a C # library), is it possible for F # to use this shorthand initialization, if not, why not?

+3
2

, . :

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

(F #) " ".

+5

, F # , #, F # . F # 14.4 :

( ) , :

  • NamedActualArgs, , .

, , #

type Something() = 
    member val Key = 0 with get,set
    member val Value = "" with get,set
    static member Create() = Something()

let a = Something(Key = 1, Value = "1") // create instance with constructor, set properties afterwards
let b = Something.Create(Key = 1, Value = "1") // create instance using factory method, set properties afterwards
+3

All Articles