Local Variables

From The Oxygene Language Wiki

Jump to:navigation, search

This is a Language topic
Feel free to add your notes to this topic below.



Local variables are normally declared (but see below) in a var section at the start of methods, e.g:

method ConsoleApp.Test;
var
  Days: Integer;
begin
  Days := System.DateTime.DaysInMonth(2005,4);
  // use Days
end;


Local variables may be initialized as they are declared, e.g.:

method CheckState: Integer;
var
  i: Integer := 9;
begin
  // use i
end;


Oxygenes's Type Inference support means that the above code can be reduced to:

method CheckState: Integer;
var i := 9;
begin
  // use i
end;

Local variables exist only for the life of the method i- they are created when the method is invoked and destroyed on exit from the method.

The var (keyword) may be on a line of its own or combined with a variable as shown above. Multiple variables of the same type can be declared together (but without initialization) and the var section can hold as many variables as you need.


More examples:

var
  a,b,c: String;
  obj1, obj2: MyObject;
  r: MyRecord;
  everTrue: Boolean := true;
  i: String := '5';


Inline Declarations

As well as declaring local variables in a var section at the start of a method, you can define a variable anywhere within a method to restrict its scope, for example:

method Test;
var
  // some variables
begin
  // some code that doesn't refer to xxx
var xxx: string
  // some code that does refer to xxx
end;

This support was first introduced for web page scripting (see Inline Scripting). For other ways of using inline variables see the for, with and using topics.

Inline declarations also support Type Inference.


See Also


Oxygene-48.png

Area: Oxygene Language
Compiler version: Oxygene 5

Language GlossaryKeywordsTypesFAQHow To

Navigation
Areas
More
Toolbox