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 };
To create an object of a named class by using an object initializer. Begin the declaration as if you planned to use a constructor. Type the keyword With , followed by an initialization list in braces. In the initialization list, include each property that you want to initialize and assign an initial value to it.
Dynamic initialization of object in C++ Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time. It can be achieved by using constructors and by passing parameters to the constructors.
In object initializer, you can initialize the value to the fields or properties of a class at the time of creating an object without calling a constructor. In this syntax, you can create an object and then this syntax initializes the freshly created object with its properties, to the variable in the assignment.
C# 3.0 (. NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor. Example: Object Initializer Syntax.
You can do it like this:
let p = new Person (Name = "John", BirthDate = DateTime.Now)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With