Reputation: 21281
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
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
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:
Object
) it would be better to use a list of a more specific type.IDisposable
as well.Upvotes: 0
Reputation:
To add to D Stanleys answer, how about so:
foreach(var o in lst.OfType<IDisposable>())
{
o.Dispose();
}
Upvotes: 1