tags:

views:

261

answers:

2

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?

A: 

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
Ray
hmm... you might be right. I guess I'm spoiled with C# letting me declare my variables wherever!
RCIX
Just tested it, didnt help. Specific error is "The value or constructor "spriteBatch" is not defined
RCIX
+2  A: 

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.)

Brian
I just tried that and it gives me the error "'let' and 'do' bindings are not permitted in class definitions unless an implicit construction sequence is used." and if i try to attach parens to the "inherit Game" part it says "This 'inherit' construction call is not part of an implicit construction sequence. Only the inheritied type should be specified at this point...".
RCIX
It sounds like you missed the first set of empty parens after SampleGame. (These parens that define a constructor are what begins the 'implicit construction sequence'.)
Brian
Yup that was it. Thanks!
RCIX
And I keep forgetting we have docs! For completeness: http://msdn.microsoft.com/en-us/library/dd233192%28VS.100%29.aspx
Brian