E
E
Evgeny Glebov2015-03-03 08:58:09
Programming
Evgeny Glebov, 2015-03-03 08:58:09

The lifetime of an object if a reference to its field was passed to a static class?

Here is an example code:

static class A
{
        static D d;
        void static Func1()
        {
                B b = new B();
                d = b.Func2();
        }
        void static Main()
        {
                Func1();
                GC.Collect();
                System.Threading.Thread.Sleep(10000);
                //b is removed?
        }
}

class B
{
        public D d = new D();
        public D Func2()
        {
                return d;
        }
}

class D
{
}

Will object b be removed from the heap after garbage collection if one of its fields is referenced by a static object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mrrl, 2015-03-03
@GLeBaTi

Will. The link goes not to the field of the object, but to the object that once lay in this field. After cleaning, only object d will remain. Now, if in d during construction there was a reference to b as a "parent", then b would also remain.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question