Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with IDisposable?

Let say I have these 3 classes.

abstract class MyBase
{
    //some base code here
}

class Foo : MyBase, IDisposable
{
    //got at least a field I should dispose
}

class Bar : MyBase, IDisposable
{
    //got at least a field I should dispose
}

I have a few classes like that. I got classes that own a List<base>. How could I dispose properly of all those classes without having to test/cast to get the proper type and then having Dispose ?

like image 513
Rémi Avatar asked Dec 16 '22 07:12

Rémi


1 Answers

Well you can use:

foreach (var disposable in list.OfType<IDisposable>())
{
    disposable.Dispose(); 
}

I'd say it's generally a bad idea to have this sort of class hierarchy though; it means clients can't just use "any instance of MyBase" in the same way, as there are additional contracts for specific types. It would be cleaner to make Base implement IDisposable, even if a few specific types didn't actually require it.

like image 176
Jon Skeet Avatar answered Dec 18 '22 12:12

Jon Skeet