1

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?

asked Jul 15, 2013 at 23:59

1 Answer 1

4

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

answered Jul 16, 2013 at 0:18
1
  • 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? Commented Jul 16, 2013 at 0:21

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.