Nulle
Nulle

Reputation: 1329

F# make member value based on member function

I have made a member function in a class. Afterwards I want to make a member value that is set to the result of this member function.

type MyType() = 
  member this.drawFilledPlanet(xCoord:int, yCoord:int, pWidth:int, pHeight:int, color) =
    let brush = new System.Drawing.SolidBrush(color)
    this.window.Paint.Add(fun e -> 
      e.Graphics.FillEllipse(brush, xCoord, yCoord, pWidth, pHeight))

  member val theSun = drawFilledPlanet(350,350,100,100, this.yellow)

I am getting the error that drawFilledPlanet is not defined.

Can someone tell me what is up?

Upvotes: 2

Views: 165

Answers (1)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

Because drawFilledPlanet is a member function, it needs a class instance on which it's to be called. If you're calling it from another member function, you would use that member's definition to name the current instance:

member this.f() = this.drawFilledPlanet ...

In your case, however, since you're defining a member val, you don't have that opportunity. In this situation, you can name the current instance at the very top of the class declaration:

type MyType() as this =
    ...
    member val theSun = this.drawFilledPlanet ... 

One thing I'd like to point out is that this definition may not have the effect that you expect. If you define theSun this way, the drawFilledPlanet method will only get executed once at class initialization, not every time theSun is accessed. Did you intend that? If no, then you need to change the definition. If yes, then why do you need this definition at all?

Upvotes: 3

Related Questions