private void Abc()
{
string first="";
ArrayList result = new ArrayList();
ArrayList secResult = new ArrayList();
foreach (string second in result)
{
if (first != null)
{
foreach (string third in secResult)
{
string target;
}
}
string target;//Here I cannot decalre it. And if I don't declare it and
//want to use it then also I cannot use it. And if it is in if condition like
//the code commented below, then there is no any complier error.
//if (first != null)
//{
// string target;
//}
}
}
I cannot understand: Why can’t I declare the variable outside the foreach loop, as compiler gives an error that the variable is already declared. The scope of the foreach (and hence the target variable) is over where I am declaring this new variable.
The scope of a local variable extends all the way up to the start of the block in which it’s declared. So the scope of your second declaration as actually the whole of the outer
foreachloop. From the C# 4 spec, section 3.7:and in section 8.5.1:
So even though the second variable hasn’t been declared at the point where the first variable occurs, it’s still in scope – so the two declarations between them violate 8.5.1.
The language was designed this way to prevent errors – it would be odd if simply moving the location of a local variable declaration within the block in which it’s declared and before its first use changed the validity of the code.