0

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...

user2706838
  • 1,061
  • 2
  • 13
  • 21

3 Answers3

4

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);
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
2

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();
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • It is actually what I need. Just free temporary storage to have opportunity to use it again. – user2706838 Apr 02 '14 at 14:10
  • @user2706838 There's no such thing as "free temporary storage". Every initialized object is created separately on a heap. It doesn't matter if you'll use the same object reference or not. I don't think you understand what a reference type is. – Tarec Apr 02 '14 at 14:15
2

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.

Tarec
  • 3,268
  • 4
  • 30
  • 47