[edit] C# Scope
Variable scope is an crucial subject in any programming language. One of the most difficult errors to debug are runtime bugs. Compilation errors are easy to pin point because the compiler tells you were the error is. A runtime bug is a bug that produces incorrect results. The program runs fine but it gives unexpected results or behavior. Trying to track variable values is a daunting task if you have hundreds or thousands of variables. If you keep track of your variable scopes you will have less headaches in the future.
When you declare a variable inside main() it is only visible in the main() block. For example, you cannot declare a variable x in main() and then try and access it in a function.
Example 1:
using System;
class Program
{
static void printX()
{
Console.WriteLine(x); //Error--Cannot access variable x
}
static void Main()
{
int x = 78; //Declared in main()
printX();
Console.Read();
}
}
Important: This program will not compile because the function printX() is trying to access a variable that is not accessible.
If you want x to accessible in the function you must pass it by value or pass by reference. Variables only have scope in the block that they are declared in.
Example 2:
using System;
class Program
{
static void Main()
{
int x = 3;
if (true) //start -- if block
{
int y = 6; //declared in if block
}
//ERROR--y is only accessible in the if block
Console.WriteLine(y);
//OK -- x is accessible
Console.WriteLine(x);
Console.Read();
}
}
Note: This program will not compile because y can ONLY be accessed in the if block
Example 3:
using System;
class Program
{
static void Main()
{
int x;
if (true) //start -- if block
{
int y = 6; //declared in if block
x = y; //x is still in Main()
}
//OK -- x is accessible
Console.WriteLine(x);
Console.Read();
}
}
Output:
6
x is still accessible because it is still in the Main block. y can only be accessed only in that particular if block.
[edit] C# Global variables
Global variables are accessible through out the whole program. To declare a global variable you must use the static or const keyword. The const keyword prevents the variable from being modified.
Example:
using System; class Program { static int a = 2; //Accessible in the whole program static void test() { Console.WriteLine(a); } static void Main() { test(); Console.Read(); } }
Output:
2
Line 4: Do you see the static keyword. This makes the variable accessible in the whole program.
- You cannot declare a static variable in the main block or in a function
- Global variables increase program performance
|