Local variables

This is a tutorial about variable scope, a variable is a means to store data within the context of the program. For example, if you wish to store a numerical value then you would not store that number in a string, but within a integer or floating point number.

There are different types of variables, integer / string etc, but the scope of a variable is the area in which the variable is defined within block of code that it is situated.

This is some c# code to demonstrate the difference between local variables and global.

class localvariable
{
       private static int value1 = 1;
 
       private static void global()
       {
              System.Console.WriteLine("Global : " + value1);
       }
 
       public static void Main()
       {
              int value1 = 0;
              System.Console.WriteLine("Local : "  + value1);
              global();
              return;
       }
}

save this as localvariable.cs and then compile up the code and run. The output should be.

Local : 0
Global : 1

and as you can tell there are two value1 within the source code whilst one is the global variable and the other is local to the Main method.

Leave a Reply

Your email address will not be published.