It is often necessary to use additional variables that will only be used in the subroutine. Such variables are called local (or local) and can only be manipulated within the subroutine in which they are created.
Local variable scope is the curly bracketed block within which it is declared. div>
The main program in C# is also a subroutine, so all variables declared inside
void Main()
are
local variables. Other subroutines don't "know" anything about the local variables of other subroutines.
Thus, it is possible to limit the scope (scope) of a variable only to the subroutine where it is really needed. In programming, this technique is called
encapsulation - hiding the variable from changing it from the outside.
If it is necessary to declare a variable that would be visible anywhere in the program (in any subroutine), then such variables are declared outside of all subroutines (see program 3 from the table below).
Such variables are called
global.
In C#, when the program starts, all global variables are automatically set to zero (boolean variables take the value false).
Analyze three programs:
1) In this program, the variable i is local. A local variable is declared inside a subroutine. |
2) Here, even if there is a variable i in the main program (with value 7), a new local variable i with value 5 will be created.
When this program is executed, the value 75 will appear on the screen. |
3) This program has a global variable i. Its value can be changed inside the subroutine, and inside the main program.
The procedure will work with the global variable i and it will be assigned a new value equal to 2. The value 2 is displayed. |
static void test()
{
int i = 5;
Console.Write("i");
}
|
static void test()
{
int i = 5;
Console.Write("i");
}
static void Main()
{
int i = 7;
Console.Write("i");
test();
}
|
using System;
class Program
{
int i;
static void test()
{
i = 2;
}
static void Main()
{
test();
Console.Write("i");
}
}
|