Search code examples
c#.netobjectgarbage-collectiondispose

How do I dispose class object from List<object>


I have a Listbox which have 3 items in which only 1 item can be selected at a time. The properties of these items are accessed from different classes - Alto,Zen,Esteem. I need to use only 1 class at a time. I am storing these classes in a list array. How can I Dispose my desired classes(according to my logic)?

List of class array

List<object> lst = new List<object>();

Add each class object to list

Alto objAlto = new Alto();
Zen objZen = new Zen();
Esteem objEsteem = new Esteem();

lst.Add(objAlto);
lst.Add(objZen);
lst.Add(objEsteem);

My logic to Dispose

enter image description here

Now my question is, how can I dispose the objects? Why I am not able to get ".Dispose"? Am I missing with any implicit conversion to avail this feature?


Solution

  • To add to D Stanleys answer, how about so:

    foreach(var o in lst.OfType<IDisposable>())
    {
       o.Dispose();
    }