bohdan_trotsenko
bohdan_trotsenko

Reputation: 5357

How do I create a class instance and fill properties in F#?

In C#, I can:

var n = new Person()
{
     FirstName = "John",
     LastName = "Smith"
};

Can I do the same in F#? I mean, to create a class and specify some properties.

Upvotes: 3

Views: 5645

Answers (3)

gradbot
gradbot

Reputation: 13862

F# also has records which are basically classes with automatically exposed properties that are meant to represent simple aggregates of named values, optionally with members.

type Person = {
    FirstName : string;
    LastName : string;
}

let p = {FirstName = "John"; LastName = "Smith"}

Upvotes: 4

kvb
kvb

Reputation: 55184

Yes:

let n = Person(FirstName = "John", LastName = "Smith")

Note that the F# approach is actually much more flexible than the C# approach, in that you can use "post hoc" property assignments with any method call (not just constructors). For example, if the Person type has a static method called CreatePerson : string -> Person which creates a new person and assigns the first name, you could also use it like:

let n = Person.CreatePerson("John", LastName = "Smith")

Upvotes: 15

Nyi Nyi
Nyi Nyi

Reputation: 788

type Person() =

    [<DefaultValue>]
    val mutable firstName : string

    [<DefaultValue>]
    val mutable lastName : string

    member x.FirstName 
        with get() = x.firstName 
        and set(v) = x.firstName <- v

    member x.LastName 
        with get() = x.lastName 
        and set(v) = x.lastName <- v

let p = new Person(FirstName = "Nyi", LastName = "Than")

Upvotes: 2

Related Questions