Posts

Showing posts from November 25, 2018

Accessing field of out of scope class instance

Image
up vote 0 down vote favorite Let's consider this class: public class A<T> { private bool _flag; public Func<T> Function { get; set; } = () => {_flag = true; return _flag; } } Now, let's imagine that the Function property somehow accesses the _flag field with both read and write in its body. Then if I use the class A like this: public Func<T> SomeFunction() { var instance = new A(); return instance.Function; } My question is what really happens, because I have originally assumed the instance would be disposed by GC when the SomeFunctions returns, which would mean the _flag would cease to exist and the Function would try to access nonexistent field when eventually called from somewhere, but that isn't what happens. The code seems to work. Is the field somehow preserv...