Alex Rivera | Logout

Hierarchy of classes that use a disposable object. Implement IDisposable on all of them?

Asked 2011-11-18T15:47:14.250
10

I have a class that uses a filestream. It needs to close the stream when the app shuts down, so I make the class implement IDisposable.

That class is a member of another class, which is a member of another class etc. All the way up to my main app.

Do I therefore have to implement IDisposable on all of these classes?

What if I change my file implementation in the future so that it closes the file after each write? I now have a whole set of classes that implement IDisposable for no reason.

I guess I'm uncomfortable with crowbarring IDisposable semantics into classes that have no need for them other than some slight implementation detail way down the chain. Are there any ways around this?

Edit
Report

1 Answer

1

It depends on how you implement the class that uses the filestream. If that class creates the filestream, then it should be responsible for disposing of it. However, if you were to change it so the method took in a filestream as a parameter, it would no longer 'own' the filestream and therefore not be responsible for disposing of it.

If the class is part of some kind of hierarchy, you can just add a filestream as a parameter starting at the top and introduce it to all methods down to where it is actually used.

For example:

public class Class1
{
    private readonly Class2 SomeObject = new Class2();

    public void DoWork1(Filestream stream)
    {
        SomeObject.DoWork2(stream);
    }
}

public class Class2
{
    public void DoWork2(Filestream stream)
    {
        // Do the work required with the Filestream object
    }
}

While I'm not sure I'd use this pattern myself, this will allow you to not have to add 'IDisposable' to any classes except for the one that originally created the Filestream object.

answered 2011-11-18T17:04:06.500

Your Answer