C# Scope
scope in C#
Simply, the scope of a type (a variable, a method, or a class) is where you can use that type in your program. In other words, the scope defines the area of the program where that type can be accessible and referenced.
When you declare a variable inside a block of code (like a method or an if statement structure), it will have a local scope, and it will be called a local-variable. Local scope means that you can’t refer to that variable outside that block of code. Consider the next example.
class Test
{
public void Test1()
{
int x = 0;
// some code goes here that uses the x variable
}
public void Test2()
{
Console.WriteLine(x);
}
}
Try to instantiate this class and you will get a compile-time error inside method Test2() telling you that the name x doesn’t exist and that’s because x is a local variable to the method Test1() and method Test2() doesn’t know anything about it. So x has a local score to method Test1() only. Consider the next example.
class Test
{
public void Test1()
{
int x = 0;
if(x == 0)
{
Console.WriteLine(“x equal to 0”);
}
}
}
Here, the method Test1() declares a local variable x (now x has a local-scope to the method). Try to instance this class and compile the code. It will work! Some beginners think that because I said that x has a local scope to method Test1() it will not be referenced from nested block (like the one we have here, the If statement) but that’s not true because any nested block inside Test1() method can refer x because x is local for the method and its all blocks of code.
hi sir,
please send more example program and explain..send mail to me
plz sir more que send on my mail id……….
thanks
WHO TO THE EXPRESEE PLACE THE QUESTIONS PLEACE SIR
I have copleted graduation in BSc with computer science in 2004-05
but i have never try in s/w firm I have waste my 2.0 precious year in local companies.After that i have completed specialization in dot net from registered s/w company/institue.Now i am currently working in one private firm but i wanted to do well in s/w industry.what i have to do now.please inform me at [email protected]