Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a private setter for a property using F#

Tags:

f#

In C#, we can declare a private setter for a property. How can this be done using F#?

Specifically, how can I ensure that the state of a property can only be changed from within the class only?

For example, how do we declare the FirstName setter property as private, as in C#?

public string FirstName { get; private set; }
type SomeViewModel() =
    inherit ViewModel()
    let mutable firstName = ""
    let mutable lastName = ""

    member this.FirstName
        with get() = firstName 
        and set(value) =
            firstName <- value
            base.notifyPropertyChanged(<@ this.FirstName @>)

    member this.LastName
        with get() = lastName 
        and set(value) =
            lastName <- value
            base.notifyPropertyChanged(<@ this.LastName @>)

    member this.GetFullName() = 
        sprintf "%s %s" (this.FirstName) (this.LastName)
like image 752
Scott Nimrod Avatar asked Dec 19 '22 22:12

Scott Nimrod


1 Answers

member this.FirstName
    with get() = firstName 
    and private set(value) =
        firstName <- value
        base.notifyPropertyChanged(<@ this.FirstName @>)

This is shown directly in the MSDN F# documentation.

like image 133
ildjarn Avatar answered Jan 19 '23 17:01

ildjarn