Arne Saknussemm
Arne Saknussemm

Reputation: 39

Visibility inside a class of objects created locally

Here it is a sample code in Windows Forms:

namespace WindowsFormsApplication1
{
    public class contained
    {
        public int value;
    }

    public class container
    {
        public List<contained> c1 = new List<contained>();

        public void add_contained()
        {
            contained tmp = new contained();
            tmp.value = 1;  // some default value
            c1.Add(tmp);
        }
    }

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            container cnt = new container();
            cnt.add_contained();
            int i = cnt.c1[0].value; // this works, why?
        }
    }
}

Practically, I have a big class "container" that manages a list of complex objects "contained". There is a procedure adding a new blank object to the list - to be modified later. Now, I ran the code above and it works, but I do not understand well why.

If the procedure "add_contained" to add a default object to the list creates one locally, I expect it disappear when the procedure exits, so the list should remain with a null pointer. Instead, I can still access the object in the list, as indicated in the last line "int i=...".

Actually, I read the garbage collector is non deterministic, it is unclear what it means, it seems it does not do things in precise moments. But, that means the above code works because it is short? If I accessed the list a bit later (ie in a more complex program) it could not work?

What is the correct way to solve the problem outlined by the code above? Thanks.

Upvotes: 0

Views: 44

Answers (1)

Sehnsucht
Sehnsucht

Reputation: 5049

When you do new contained() a new object is created and stored "somewhere".
Then a reference to it is assigned to tmp.
That same reference is in turn added to the list and you exit the method.
At that point the variable tmp is "destroyed" but the object is still in memory (because it's still referenced through the List).

If at some point you remove the list item, the reference on that object ; and there are no other reference on that object ; it becomes eligible for collection, meaning the GC can free it's memory.

Upvotes: 2

Related Questions