0

Looking at the following code:

class Class1
{
    private List<object> _listOfAnything;

    ~Class1() //is it worth it?
    {
        //set null to all items of the list
        if (_listOfAnything != null)
        {
            if (_listOfAnything.Count > 0)
            {
                for (int i = 0; i < _listOfAnything.Count; i++)
                {
                    _listOfAnything[i] = null;
                }
                //clear list
                _listOfAnything.Clear();
            }
            //set list to null
            _listOfAnything = null;
        }
    }

    public void DoSomething()
    {
        //create list and add items to it
        _listOfAnything = new List<object>();
        _listOfAnything.Add(new object());
        _listOfAnything.Add(new object());
        _listOfAnything.Add(new object());

        //do something
    }
}

class Class2
{
    private void DoSomething()
    {
        //instanciate Class1
        Class1 class1 = new Class1();
        //do something with Class1
        class1.DoSomething();
        //set null to Class1
        class1 = null; //do I need to set it no null?
    }
}

Do I really need to set Class1 to null and clear Class1._listOfAnything?

Wiley Marques
  • 485
  • 3
  • 16

3 Answers3

4

It is not necessary to clear the list the garbage collector will take care of it.

Best way to dispose a list

Community
  • 1
  • 1
Marko
  • 2,734
  • 24
  • 24
1

This is a waste and accomplishes nothing Garbage Collector can't already do.

However, lets say you needed something to happen to each item BEFORE the instance of Class1 is obliterated, consider looking at IDisposable. Remember, the destructor is only called when the GC takes care of the instance. Not when the instance loses scope.

poy
  • 10,063
  • 9
  • 49
  • 74
-1

I don't believe that would be required since the List object would be destroyed as soon as it's out of scope and the .Net compiler GC (garbage collector) would clear the memory of.

Suyash Khandwe
  • 386
  • 3
  • 11
  • This isn't quite true. The destructor is not called when the `List` instance loses scope. The instance is only destroyed when the GC gets it. – poy Jan 08 '14 at 19:32
  • @Andrew - So you mean that the List instance would still be alive even after the holder object (object of Class1) is out of scope? – Suyash Khandwe Jan 08 '14 at 19:47
  • 2
    @Yes. Its only "dead" once the GC gets around to it. – poy Jan 08 '14 at 20:06