Sorry if this is basic, but I'm still wrapping my head around F#.
I want to do this:
type Person(user:User) as this =
member val Name = "" with get, set
user.UserId <- this.Name
But that gives me the error Unexpected identifier in member definition
.
This compiles:
type Person(user:User) as this =
do
user.UserId <- this.Name
member val Name = "" with get, set
But gives me an InvalidOperationException
at runtime.
I've settled for this:
type Person(user:User) =
member val Name = "" with get, set
member this.Setup() =
user.UserId <- this.Name
But I don't like having to call person.Setup()
each time.
What's the best F-Sharpy way to do this?
1 Answer 1
You can do this with an explicit constructor to force the code for initializing the member functions to be run before your other code as follows
type User() =
member val UserId = "" with get,set
type Person private () =
member val Name = "" with get, set
new (user:User) as this =
Person()
then user.UserId <- this.Name
This is due to the fact that the initializer code is run in the constructor, so you must force it to run to completion before acccessing the properties
-
Is there a way to do that and only allow the second constructor (passing in the User object) to be called? I.e., some way of making the first (explicit) constructor private?Ken Smith– Ken Smith07/16/2013 00:21:36Commented Jul 16, 2013 at 0:21