Initializing an F # Object Using the Constructor

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

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

You can initialize it so that is nice:

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

How would you initialize it in F # if the C # class also had such a constructor:

 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 
+6
source share
2 answers

Using equivalent F # syntax for auto properties might look like this. You can combine 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 
+8
source

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

 > let ub = UriBuilder("http://blog.ploeh.dk", Path = "about");; val ub : UriBuilder = http://blog.ploeh.dk:80/about 
+5
source

Source: https://habr.com/ru/post/1013635/


All Articles