Page Stats
Visitor: 464
C#.Net - Scope of a Variable
Variable whose scope covers a single method are known as local variable.
Variable whose scope covers multiple methods are known as global variables. In C#.Net you must use either static or const keyword for declaring a global variable. If you want to modify the value of the global variable, use static, as constant variable prohibits any change in the value of a variable.
Example 1: Local and Global variable.
using System;
namespace ConsoleApplication1
{
class Program
{
//const int a = 10; //global variable
static int a = 10; //global variable
static void method()
{
int b = 20; //local variable
Console.WriteLine("Variable inside method = " + a);
}
static void Main(string[] args)
{
int c = 20; //local variable
a = 50;
method();
Console.WriteLine("Variable inside main method = " + a);
Console.ReadLine();
}
}
}
Variable inside method = 50
Variable inside main method = 50
Variable inside main method = 50