Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Object Initialization with a Constructor

I know that in F# if you have a C# class of the format:

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

You can initialize it like so, which is nice:

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

However how would you initialize it in F# if the C# class also had a constructor like this:

public class Person {
    public Person(int id)
    {
        Id = id
    }

    public int Id {get; private set;}
    public DateTime BirthDate { get; set; }
    public string Name { get; set; }
}

Are we forced to use this structure instead?

let p = new Person (123)
p.Name <- "John"
p.BirthDate <- DateTime.Now
like image 319
Luke Merrett Avatar asked Dec 30 '16 10:12

Luke Merrett


2 Answers

Using the equivilent F# syntax for auto properties might look like this. You are able to combine the constructor and property initialization as follows:

type Person(id : int) =
    member val Id = id with get,set
    member val BirthDate = DateTime.MinValue with get,set
    member val Name = "" with get,set

let p = Person(5, Name = "Stu")
p |> Dump
like image 114
Stuart Avatar answered Oct 28 '22 09:10

Stuart


The System.UriBuilder BCL class looks like the Person class in the OP, so I'll use that as an example:

> let ub = UriBuilder("http://blog.ploeh.dk", Path = "about");;    
val ub : UriBuilder = http://blog.ploeh.dk:80/about
like image 35
Mark Seemann Avatar answered Oct 28 '22 11:10

Mark Seemann