M
Marc Gravell
As a follow-on question... where does variable i 'live'. It's local
a field on an object that the C# compiler creates for you. The rules
for the scoping of each "captured" variable is quite tricky... but but
*conceptually* what we are talking about (without using captures)
would be comparable to the following (although the compiler implements
it differently):
class SomeObject {
int i;
void SomeMethod() {
Debug.Assert(i != 2);
}
}
....
SomeObject obj = new SomeObject(); // obj instance is managed
for(int tmp = 0; tmp < 2; tmp ++) { // tmp lives on the stack
obj.i = tmp; // i lives on obj
Thread t = new Thread(obj.SomeMethod);
}
note that there is only a single "obj", and hence all share an "i".
Now compare to the version with a "j" introduced (see my other post in
this topic):
class SomeOtherObject {
int j;
void SomeOtherMethod() {
Debug.Assert(j != 2);
}
}
....
for(int i = 0; i < 2; i++) { // i lives on the stack
SomeOtherObject obj = new SomeOtherObject(); // obj instance is
managed
obj.j = i; // j lives on obj
Thread t = new Thread(obj.SomeOtherObject);
}
in this latter case, each loop iteration gets a different object, and
hence a different "j"
Please note: I have simplified the behavior to make a simple example.
Marc
Nope, it doesn't live on the stack - it is "captured", so it lives asand
a value type, so lives on the local stack...
a field on an object that the C# compiler creates for you. The rules
for the scoping of each "captured" variable is quite tricky... but but
*conceptually* what we are talking about (without using captures)
would be comparable to the following (although the compiler implements
it differently):
class SomeObject {
int i;
void SomeMethod() {
Debug.Assert(i != 2);
}
}
....
SomeObject obj = new SomeObject(); // obj instance is managed
for(int tmp = 0; tmp < 2; tmp ++) { // tmp lives on the stack
obj.i = tmp; // i lives on obj
Thread t = new Thread(obj.SomeMethod);
}
note that there is only a single "obj", and hence all share an "i".
Now compare to the version with a "j" introduced (see my other post in
this topic):
class SomeOtherObject {
int j;
void SomeOtherMethod() {
Debug.Assert(j != 2);
}
}
....
for(int i = 0; i < 2; i++) { // i lives on the stack
SomeOtherObject obj = new SomeOtherObject(); // obj instance is
managed
obj.j = i; // j lives on obj
Thread t = new Thread(obj.SomeOtherObject);
}
in this latter case, each loop iteration gets a different object, and
hence a different "j"
Please note: I have simplified the behavior to make a simple example.
Marc