Local Variables

The var statement is used to declare and optionally initialize a new local variable in the current scope. The variable will be available for all code below its declaration, up until the end of the current scope – that is either to the end of the current method, if the variable is declared on that level, or to the end of the block Statement that includes the declaration.

In its simplest form, a variable declaration starts with the keyword var, followed by a new unique name for the variable, a colon (:), and the type.

var i: Integer;

Optionally, the declaration can be followed by an initial value for the variable, assigned via the := operator. Variable declarations without initializer will be initialized to the default value of their type.

var i: Integer := 5;

Type Inference

When an initializer is provided and a concrete type can be inferred from it, the type name can optionally be omitted. This is referred to as type inference.

var i := 5;

It is important to note that – unlike in scripting languages such as JavaScript – the variable will still be strongly typed, in the above case to be an Integer. Omitting the type name is merely a convenience (and sometimes a necessity, when using Anonymous Types which have no name), but that does not mean that the variable is untyped.

Oxygene will use the type of the expression to the right of the := operator to infer the type, if possible. For numeric literals, the inferred type will be the smallest integer that can fit the literal, but no smaller than a 32-bit signed integer.

Declaring Multiple Variables in one Statement

Multiple variables of the same type can be declared in one statement by separating them with a comma. When using this option, no initializer may be provided, as it would be ambiguous whether the initialization would apply to all variables or only to the last one.

var a, b: Integer;

Storage Modifiers (Cocoa)

On Cocoa only, the type name of a field declaration can be amended with the weak, unretained or strong Storage Modifier keywords, with strong being the default.

var lValue: weak String;

To specify a Storage Modifier, the type cannot be inferred, but must be explicitly specified. Inferred types will always be considered strong.

Modifiers

Similar to type members, the following modifiers are allowed on local variables:

  • pinned — can be applied to pointer and class reference variables on the .NET platform to indicate that the target object will be pinned to a fixed location and may not be moved by the Garbage Collector while the variable is alive (applicable on platforms that use GC, namely .NET and Java).
  • readonly — indicates that the variable may not be altered after its declaration. For obvious reasons, this only makes sense for variables that have an initializer.
var i := 5; readonly;
var a := new Customer; pinned;

See Also