Global and local variables

SSharp S# API

DropDown image DropDownHover image Collapse image Expand image CollapseAll image ExpandAll image Copy image CopyHover image

Global variables are variables that are accessible in every scope. Such variables are used extensively to pass information between sections of code that don't share a caller/callee relation like functions.

Example:
 

// Creates a global variable "g_variable1" with value of 100
g_variable1 = 100;
// Creates a global variable "g_variable2" with value of 200
g_variable2 = g_variable1 + 100;
function MyFunction1() { ... }
function MyFunction2() { ... }
 

Local variables are variables that are given local scope. Such variables are are accessible only from the function or block in which it is declared. Local variables are contrasted with global variables.

Example:

 
// Creates a global variable
my_variable = 100;
function MyFunction()
{
  // Creates a local variable
  my_variable = 200;
}

 

To avoid naming conflicts when referencing local and global variables S# provides a special global: keyword that provides access to global scope Example:

// Creates a global variable
g_variable = 100;
function MyFunction()
{
  // Creates a local variable
  g_variable = 200;
  Console.WriteLine("Local variable value: " + g_variable);
  Console.WriteLine("Global variable value: " + global:g_variable);
}
// Invokes "MyFunction" function
MyFunction();

 

When running the example above you will get the following output as a result:

Local variable value: 200

Global variable value: 100

Var Keyword

There is ability to specify that variable should be created in exactly that scope in which expression will be evaluated. This is the purpose of var keyword:

var a = 2;