In the body of a method, you can also declare variables that would be used internally. A variable declared in the body is referred to as a local variable. It cannot be accessed outside of the method it belongs to. After declaring a local variable, it is made available to the method and you can use it.
As mentioned with functions, C# doesn’t have the notion of global variables (in C/C++,
Visual Basic, Pascal, etc, a global variable is one that is declared outside of any class; such a variable is made available to any function, or even file, of the same program without being declared again where needed). Still, if you want to use the same variable in various methods of the main class, you can declare it outside of any method. The variable must be declared as static. That is, you must type the static keyword to its left when declaring it. Here is an example:
Using System;
Class Exercise
{
Static double Length;
Static void welcome()
{
console. WriteLine (“welcome to the wonderful world of c#”);
}
Static void Main ()
{
Welcome();
console. WriteLine ();
}
}
After declaring such a variable, you can access from any method that belongs to the same class. Here is an example, to understand the concept of static variable.
Use of static variable
using System;
class Cylinder
{
static double Length;
static double Width;
static double Area;
static double Get The Length ()
{
double Len;
console. Write (“Length: “);
Len= double. Parse (console. Read Line ());
return 1en;
}
static double GetThewidth()
{
double w;
console. Write \(“width: “);
w = double. Parse (console. Read Line ());
return w;
}
static void AreaRect ()
{
console. WriteLine (“Enter the Length and width of Rectangle “);
width = Get The width();
Length = Get The Length();
Area = Length * width;
}
static void show Area()
{
console. Write Line(“\n characteristics of Rectangle”);
console. write Line(“Length: “+ Length);
console. Write Line(“width :”+ width);
Console. Write Line(“Area :”+ Area); }
}
static void Main()
{
AreaRect ();
Show Area() ;
console. Write Line (); }
}
}
OUTPUT:
Enter the Length and Width of Rectangle
Length: 38.24
Width: 32.58
Characteristics of Rectangle
Length: 38.24
Width: 32.58
Area : 1245.85