Statements: var

Declares a local variable. Local variables and arrays allow you to store intermediate results during the evaluation of expressions.

Syntax

Form 1:

vartype‑expressionvariable‑name;

Form 2:

vartype‑expressionvariable‑name=initialization‑expression;

Discussion

In its simplest form, the declaration determines the name of the new variable and the data type of values this variable can store at the runtime. Optionally, the declaration can include an expression to immediately initialize the just declared variable. If the initialization-expression is omitted, the variable is initialized implicitly with its data type specific zero value (an empty string "", an empty set [], a transparent color #00000000, boolean value false or even the number 0). As such it is legal to evaluate a non-explicitly initialized local variables. For example:

var string text1 = "Hello"; var string text2; // Read the value of a locally declared variable var string result = text1; // result = "Hello" // Modify the Variable text1 = text1 + " world"; // text1 = "Hello world" // Trying to read a non-explicitly initialized variable results // in the respective zero value var string result = text2; // result = ""

The var statement can occur everywhere within the method or within a nested block statement wherever regular statements are allowed. The blocks serve as individual scopes for all enclosed local variables and arrays. In other words, the variables are valid within the respective block only. Outside the block, these definitions are not available and their contents are lost. For example:

if ( operand1 ) { // Following variables are valid within this block only var rect v1 = SomeTextView.Bounds; var string v2 = SomeTextView.String; [ ... ] } var rect v1 = OtherTextView.Bounds; var string v2 = OtherTextView.String; [ ... ]