Hi,
Very strange, this code works:
for (int i = 0; i < nItems; i++)
{
string[] parts = items[i].Split('\t');
......
}
It looks the same string array "parts" is created nItems times but without any error, or C# clever enough to created only onece?
Loading
VulpesPosted Jan 8, 2014, 5:30 PM
So this isn't allowed:
void MyMethod()
{
int a = 3;
for(int i = 0; i < 10; i++)
{
int a = i + 3;
Console.WriteLine(a);
}
}
because the scope of the 'outer' a includes the scope of the 'inner' a.
However, you can do this because the scope of the 'i's and the 'a's doesn't overlap - they only exist within their respective 'for' statements:
void MyMethod()
{
}
The reason the first situation isn't allowed is because, if it was, then there would be no way to access the 'outer' a from within the for loop.
However, this rule doesn't prevent you declaring a local variable with the same name as a field because you can always access the field by prefixing it with 'this':
class MyClass
{
private int a = 2; // field declaration
Whilst, on the face of it, this:
int a;
for (int i = 0; i < 10; i++)
{
a = i + 3;
Console.WriteLine(a);
}
seems more efficient than this because you're only declaring the local variable, a, once:
in practice, there's no appreciable difference because the 'inner' a always uses the same memory location on the stack.
DavePosted Jan 8, 2014, 5:46 PM
DavePosted Jan 8, 2014, 5:24 PM
string[] parts = items[i].Split('\t')
looks being excuted more than onece in a loop? Am I right?
DavePosted Jan 8, 2014, 4:36 PM
Thank you.
I think we cannot declare the same array/variable more than once within a procedure like Main?
Is this works in a Loop? Or in any other procedure?
VulpesPosted Jan 8, 2014, 4:08 PM
So, on the final iteration, 'parts' will contain the result of items[nItems-1].Split('\t').
As each re-assignment to the local variable takes place, the previous array object will no longer be referenced and will therefore become eligible for garbage collection.