About
In this code snippet, we will take a look at variable scope and code blocks in C#.
A code block is the space between two { }. Variables can be considered out of or in scope depending on whether they are accessible or not from a particular code block.
Let’s just have a look at the code below.
Code:
using System;
namespace scope
{
class Program
{
static void Main(string[] args)
{//start of code block
//A set of { } makes a code block.
//You can nest a code block inside another code block.
//Variable a is accessible from everywhere inside this code block(but not outside of it)
//including any other nested code block inside this code block.
int a = 5;
if (true)
{ //start of code block 1
//Variable b is accessible from everywhere inside code block 1(but not outside of it).
//Including any other nested code block inside code block 1.
int b = 9;
if (true)
{ //start of code block 2
//And so on ... for very further nested code block ...
int c = 4;
if (true)
{ //start of code block 3
int d = 14;
//As you can see a is in scope here.
a = d;
} //end of code block 3
} //end of code block 2
} //end of code block 1
//But d is outside of scope here and we get an error.
d = 15;
Console.ReadLine();
}//end of code block
}
//Another scope example with a class.
class MyClass
{
//MyClassVariable is only available in this class and to other members of this class.
int MyClassVariable = 10;
void MyMethod()
{
//Only available inside this method.
int MyMethodVariable = 10;
Console.WriteLine(MyMethodVariable);
Console.WriteLine(MyClassVariable);
}
void MySecondMethod()
{
//MyMethodVariable is not available in MySecondMethod.
Console.WriteLine(MyMethodVariable);
Console.WriteLine(MyClassVariable);
}
//NOTE:
//The members of this class can be set to be accessible/inaccessible from outside of this class.
//This can be done by changing the access modifiers private/public/protected.
//See my post on access modifiers for more information on the topic.
}
}





