Object initialization syntax
Asked Answered
S

3

115

I'm just starting out with F# and I can't find the syntax to do object initialization like in C# 3.

I.e. given this:

public class Person {
  public DateTime BirthDate { get; set; }
  public string Name { get; set; }
}

how do I write the following in F#:

var p = new Person { Name = "John", BirthDate = DateTime.Now };
Stepup answered 16/12, 2008 at 16:44 Comment(0)
O
154

You can do it like this:

let p = new Person (Name = "John", BirthDate = DateTime.Now)
Older answered 16/12, 2008 at 16:54 Comment(1)
By convention new is only used with disposable classes.Leading
F
100

the answer from CMS is definitely correct. Here is just one addition that may be also helpful. In F#, you often want to write the type just using immutable properties. When using the "object initializer" syntax, the properties have to be mutable. An alternative in F# is to use named arguments, which gives you a similar syntax, but keeps things immutable:

type Person(name:string, ?birthDate) =
  member x.Name = name
  member x.BirthDate = defaultArg birthDate System.DateTime.MinValue

Now we can write:

let p1 = new Person(name="John", birthDate=DateTime.Now)
let p2 = new Person(name="John")

The code requires you to specify the name, but birthday is an optional argument with some default value.

Funds answered 16/12, 2008 at 18:19 Comment(1)
Thanks Tomas, but in my case Person is in another assembly and I can't change it :(Stepup
E
6

You can also omit the new keyword and use less verbose syntax:

let p = Person(BirthDate = DateTime.Now, Name = "John")

https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/members/constructors

Examination answered 10/9, 2019 at 8:6 Comment(1)
new-less syntax looks quite better in F#Dymphia

© 2022 - 2024 — McMap. All rights reserved.