Question

Lets say I have next class:

class MyClass
{
   public string Id {get; set;}
   public List<string> Data = new List<string>();
}

I need to fill some list of MyClass instances in next way;

// member
private List<MyClass> m_instances = new List<MyClass>();

// some function

public void MyFunc()
{
    MyClass instance = new MyClass();

    for (/* something */)
    {
        instance.Id = "id1";
        instance.Data.Add("data1");

        if (/* something */)
        {
            m_instances.Add(instance);
            instance = new MyClass(); // (!!!!)to clear data
        }
    }
}

Will GC handle it in correct way?

P.S. I could not free properties manually because there are a lot of properties...

Was it helpful?

Solution

It's much simpler to just move the object instantiation into the loop, at the top of the loop:

for (/* something */)
{
    MyClass instance = new MyClass();
    instance.Id = "id1";
    instance.Data.Add("data1");

    if (/* something */)
    {
        m_instances.Add(instance);
    }
}

OTHER TIPS

You can, but it does not clear the instance in the List. It will only create a new instance of MyClass and assign in to instance.

You have to set the instance itself to a different value, like this:

m_instances[index] = new MyClass();

Or

m_instances[m_instances.IndexOf(instance)] = new MyClass();

instance = new MyClass(); // (!!!!)to clear data - it's not clearing the data, it's constructing a new object. Just put MyClass instance = new MyClass(); inside your loop. Even if you would do it the proper way

MyClass instance;
for (/* something */)
{
    if(something)
    {
        instance = new MyClass();
        instance.Id = "id1";
        instance.Data.Add("data1");
        m_instances.Add(instance);
    }
}

Then it would not matter, because compiler will generate the same code as if you would create and initialize the object inside the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top