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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With