If an anonymous method captures a field of an object, would that whole object be caputed and not being garbarge collected?
So following is a snippet, what I want to know is whether SessionKeeper will hold the object f as long as the anonymous method is not explicited removed from the list :
class Foo
{
public String State { get; set; }
public void KeepState()
{
SessionKeeper.Singleton.Add(delegate
{
//do something with this.State
});
}
}
Foo f = new Foo();
f.KeepState();
The question presupposes a falsehood and therefore cannot be sensibly answered. Anonymous methods only “capture” locals, formal parameters and
this, never fields of classes. Fields of classes, elements of arrays, and so on, are not considered “outer variables” for the purpose of closing over.Now, if the field is a field of a local then you’ve used the local, and the local will be captured. But it would be captured regardless of whether you used it for its fields or not; the fields don’t come into it.