Site icon Freshershome

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.

Exit mobile version