Sarath Subramanian
Sarath Subramanian

Reputation: 21281

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?

Upvotes: 1

Views: 1863

Answers (2)

D Stanley
D Stanley

Reputation: 152521

Why I am not able to get ".Dispose"?

Becasue yout list is of tyoe List and Dispose is a method of the IDisposable interface. If your list was of type IDisposable (or some type that implements IDisposable), then you could call Dispose directly.

Am I missing with any implicit conversion to avail this feature?

There's not an implicit conversion, but if the objects implement IDisposable you can explicitly cast them:

foreach(object o in lst)
{
   if(o is IDisposable)
      ((IDisposable)o).Dispose();
}

However there's a couple of design oddities that I see:

  • A list of objects is usually a code smell. If the objects all implement a common interface or have a common base class (other then Object) it would be better to use a list of a more specific type.
  • Typically whatever creates an object is responsible for disposing of it. An alternative is to make whatever contains the objects implement IDisposable as well.

Upvotes: 0

user604613
user604613

Reputation:

To add to D Stanleys answer, how about so:

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

Upvotes: 1

Related Questions