RCIX
RCIX

Reputation: 39437

F# Assign Value to Class Member In Method

I'm playing around with F# in VS 2010 and i can't quite figure out how to assign a value to a member in a class.

type SampleGame = 
    class 
    inherit Game
    override Game.Initialize() = 
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)
        base.Initialize()
    val mutable spriteBatch : SpriteBatch
    end

I thought this was right but it says it cannot find "spriteBatch". is this the correct way to make members for objects, or is there a better way?

Upvotes: 0

Views: 866

Answers (2)

Brian
Brian

Reputation: 118865

You should prefer this syntax for defining classes

type SampleGame() =     
    inherit Game()    
    let mutable spriteBatch : SpriteBatch = null
    override this.Initialize() =         
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)        
        base.Initialize()    

where you define at least one constructor as part of the class definition (the parens after the first 'SampleGame' in code above), and then next use 'let' and 'do' to initialize/define instance variables and run code for that constructor, and then finally define methods/properties/overrides/etc. (As opposed to your syntax which has no constructor parens after the type name and uses 'val' for instance variables.)

Upvotes: 3

Ray
Ray

Reputation: 3109

I think you have to declare your variable before you use them.

type SampleGame = 
    class 
    inherit Game

    val mutable spriteBatch : SpriteBatch

    override Game.Initialize() = 
        spriteBatch <- new SpriteBatch(this.GraphicsDevice)
        base.Initialize()
    end

Upvotes: 0

Related Questions