This is clearly not appears like it wouldn\'t be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or ar
You need to capture the value of the variable within the closure/delegate, else it can be modified, like you saw.
Assign currentValue to a variable local (inside) to the delegate.
currentValue is no longer a local variable: it is a captured variable. This compiles to something like:
class Foo {
public string currentValue; // yes, it is a field
public void SomeMethod(object sender, EventArgs e) {
Response.Write(currentValue);
}
}
...
public Page_Index() {
Foo foo = new Foo();
foo.currentValue = "This is the FIRST value";
this.Load += foo.SomeMethod;
foo.currentValue = "This is the MODIFIED value";
}
Jon Skeet has a really good write up of this in C# in Depth, and a separate (not as detailed) discussion here.
Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.
This is different to java: in java the value of a variable is captured. In C#, the variable itself is captured.
I suppose more the question I am asking is that how is it working with a local variable [MG edit: "Ack - ignore this..." was added afterwards]
That is the point; it really isn't a local variable any more - at least, not in terms of how we normally think of them (on the stack etc). It looks like one, but it isn't.
And for info, re "not good practice" - anonymous methods and captured variables are actually an incredibly powerful tool, especially when working with events. Feel free to use them, but if you are going down this route, I would recommend picking up Jon's book to make sure you understand what is actually happening.