codecandle logo




 

C# - Basics - Variables - Variable scope in C#


Related: C# Tutorial

Date: 12.09.2011

Variable scope


Variable scope in C# indicates the scope levels of variables that where they are accessible. Scope refers to the code block that starts with bracket and ends with closing bracket.

How Variable scope works in C#


When a variable is declared in C#, it is accessible for a scope. Appliance of variable scope is as follows:

- A Class variable (member variable as C++ term) is accessible within its container class (till Class ends with closing bracket)
- A local variable is in a scope until the scope is finished with closing bracket
- A local variable in a for, while or similar loop statement is in scope until the loop is finished with closing bracket. Variable scope in loop example:


...
bool v_condition = true;
while (v_condition)
//loop scope starts
{
string v_aWord = "nevada";
Console.WriteLine(v_aWord);//OK: variable is in scope till closing bracket
}
//loop scope ends
Console.WriteLine(v_aWord);//ERROR: variable is not in scope
...


Variable scope in Classes of C#


Above variable scope rules applies similar to the Classes and its methods. When a variable is declared in a Class as field (member variable in C++ term), variable is in scope until its container Class ends. Example:



class CL_employees
//Class scope starts
{
//a field of Class
string CLv_employeeAge;

//a method of Class
void CLf_displayAge()
{
Console.WriteLine(CLv_employeeAge);//OK: age variable is in scope till Class
definition ends

}

}//Class scope ends



Variable scope in Functions of C#


Similar to the above appliance: a variable which is defined in a function is in scope within container function.



void f_aFunction()
//function scope starts
{
//a variable
int x = 5;
//access to variable
Console.WriteLine(x);//OK: variable in scope
}
//function scope ends



After a scope ends, it indicates that the same named variable can be declared and can be accessed. Since it will refer to a new variable. If the same named variable is declared in same scope, it is compiler error due to the ambiguity and compiler ends up with scope clash.





Area: articles

Reference resources: http://msdn.microsoft.com/en-us/library/ms364047%28v=vs.80%29.aspx
Tags: C# - Variable scope

Catagory layer 1: Programming
Catagory layer 2: Languages

Code layer 1: Languages
Code layer 2: csharp
Code layer 3: Basics
Code layer 4: variables
Code layer 5: variable-scope

Reader layer 1: beginner

Sector layer 1: C# programmer

Fuzzy layer 1: What is variable scope in C#
Fuzzy layer 2: How variable scope works in C#

Nodes: Languages\C# (1)
  • comment icon
  • Comments Section
Related topics:

Chat section


[ Copy this | Start New | Full Size ]