-1

I want to know if Remove() method of List dispose(destruct) element?

In my code, I have a List type of Timer

List<Timer> timerlist;


Timer t = new Timer();
t.Tag = ApptNo.ToString();
t.Interval = ApptInterval * 1000;
t.Tick += tm_Tick;
timerlist.Add(t);
t.Enabled = true;
t.Start();


foreach (Timer t in timerlist)
{
    if (string.Equals(t.Tag, ApptNo.ToString()))
    {
        t.Stop();
        timerlist.Remove(t);
        break;
    }
}

My point of question is whether I should dispose timer object t manually or automatically disposed from timerlist.Remove(t). If t.Dispose() should be called, where should I call it?

Don
  • 23
  • 1
  • 4
  • 6
    no, it doesn't dispose - you have to do that yourself, presumably right before the `break` – Marc Gravell Apr 24 '19 at 15:19
  • 2
    Possible duplicate of [RemoveAt(x); Does it dispose the element x?](https://stackoverflow.com/questions/16181693/removeatx-does-it-dispose-the-element-x) or [Does calling Clear disposes the items also?](https://stackoverflow.com/q/49428888/150605) – Lance U. Matthews Apr 24 '19 at 15:23

1 Answers1

2

No, removing from a list doesn't dispose anything - because in the general case, simply being in a list doesn't mean lifetime ownership; an object could be in multiple lists (or none), and as fields on multiple objects (or none), and in multiple local variables (or none) - so a list cannot assume that removal means the object is doomed.

So: do that yourself when you're sure the object's lifetime is over. In this case, presumably right before you break.

Note that it will still be garbage collected at some time after the point that is not reachable from anywhere, but usually you should ensure you do your own disposal of IDisposable types, especially for timers (since timers are essentially "roots").

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900