Static
From REALbasicWiki
The static keyword is used to declare a static variable. A static variable belongs to the method in which is declared, and its value persists between invocations of the method (whether global, shared, or object)
Contents |
[edit] Syntax
static variableName as Type [ = InitialValue]
The optional initial value may be a literal, another variable, or the value returned by a function.
static s as String = "foo" static d as new Dictionary static f as FolderItem = DesktopFolder
Note that the assignment of InitialValue to the variable happens only once, the first time the code is executed.
[edit] Examples
First is a "hello-world" sort of example.
Function Pi() as Double static theValue as Double = 4*ATan(1) return theValue End Function
Next is a use of a static variable to add a unique identifier to objects of a class; this can be useful for debugging.
Given a class Class1, add a private property pID as Integer. Then add a computed property ID as Integer, implemented as follows.
Function Get() as Integer return me.pID End Function Sub Set(value as Integer) End Sub
The purpose of the computed property is to provide read-only access to the value of pID by other objects.
Now we add a constructor to Class1.
Sub Constructor() static nextID as Integer = 0 nextID = nextID + 1 me.pID = nextID End Sub
The nth Class1 object created at runtime will have ID = n.
[edit] Scope
Like local variables, static variables have scope limited to the block in which they are declared. Consider the following examples.
Sub DemonstrateMethodScope() static foo as Integer //more code here End Sub
In this method, the static variable foo is avaiable to all code following its declaration.
Sub DemonstrateBlockScope()
//some code
for i as Integer = 0 to 43
static foo as Integer
next
//more code
End Sub
In this example, the static variable foo is visible only within the for-next block. Its value persists, as with any static variable.
[edit] Memory Management
Object references held in static variables are not released at application exit. This will prevent the destructor of an object from being called. (Feedback)
