I’m sure this is elementary but I haven’t figured it out yet.
I have a simple program, in it a Class. In the MainWindow, I’ve added a property TheClass of type Class, scope Public. This does not seem accessible anywhere (run time exception NilObject). In a button action event, I cannot access it unless I declare it with Var TheClass New Class, then it works - but only in that button action after which is goes out of scope as expected. I want to use TheClass throughout the program. How do I do that and why?
I’d have thought the adding of it as a property at the MainWindow level would have instantiated it, and as it is public it would be available.
Do I need to Var the properties of the class? This Class has two properties, “name” and “motion()”. I assumed they’d get instantiated along with the class instance.
Also there’s the Introduction to Programming Textbook that Xojo offers which goes into the specifics of instantiating classes in section 2.2 A Place For Your Stuff
These can do the same thing, but they’re not directly equivalent. The var statement is a keyword. You can find information about what var does very early on in the textbook.
The answer that I just provided can be found in section 2.2 A Place For Your Stuff on page 22. I’m sure there’s more in there for you to discover.
Edit: Updated my answer to “not directly equivalent”
In the language reference under Var, they are suggested to be equivalent. I’ve read all of page 22, and doing exactly what they say, it does not work.
Now, Kem sheds some light on it. I had to add a Property to the MainWindow, then instantiate it with TheClass = New Class. That seems to work, and begins to make some sense: the added property is equivalent to the Var statement but not limited to the Open event scope, but does not instantiate a class instance. The instantiation TheClass = NewClass is not limited in scope. Thanks Kem.
creates a variable of type class, called TheClass. Its initial value will be Nil.
This:
TheClass = new Class
initialises TheClass to point at a new object of type Class. This new object will have any properties that you added to Class, with whatever initial values you assigned to them. If you created a Constructor method for this class, then that will be executed at “new” time and may well initialise some properties to various values.
You can do all this in one step as:
Var TheClass as new Class
but personally I prefer to avoid that.