A global variable is a variable which is accessible throughout the program until the program is running. Global variables are generally static variables so that the initial values must be expressed as constants, rather than expressions. Global variable belongs to every function in the program as well as accessible in every scope, so that global variable can be modified from anywhere and any part of the program may depend on it.
We can define the global variable in following ways:
1. Define a global variable constant by using below syntax
public const return type GlobalVariableName=value;
2. Define a global variable as a static value protected by access routine by using below syntax
public static class ClassName
{
static returntype GlobalVariableName;
public static returntype VariableName
{
get
{
return GlobalVariableName;
}
set
{
GlobalVariableName = value;
}
}
}
class SampleProgram
{
static void Main()
{
ClassName.VariableName=value;
}
}
3. Define a global variable as Global static field by using below syntax
public static class ClassName
{
public static returntype GlobalVariableName;
}
class SampleProgram
{
static void Main()
{
ClassName.GlobalVariableName =value;
}
}
A sample C# code for defining a global variable
namespace GlobalConsoleApplication1
{
public static class SampleGlobal
{
public const string GlobalStr = "Hello World"
public static bool GlobalBool;
static int GlobalInt;
public static int GlobalValue
{
get
{
return GlobalInt;
}
set
{
GlobalInt; = value;
}
}
}
}
using System;
using GlobalConsoleApplication1
namespace ConsoleApplication1
{
class SampleProgram
{
static void Main()
{
Console.WriteLine(SampleGlobal.GlobalStr);
SampleGlobal.GlobalValue = 7890;
Console.WriteLine(SampleGlobal.GlobalValue);
SampleGlobal.GlobalBool = false;
Console.WriteLine(SampleGlobal.GlobalBool);
Console.ReadKey();
}
}
}
0 Comment(s)