Tim Meyer
Tim Meyer

Reputation: 12600

Should I really implement IDisposable in this case?

I'm currently using NDepend while developping a C# application. I get a violation on a rule stating that "Types with disposable instance fields must be disposable".

I know you should in fact do that when you do something like this:

class SomeClass : IDisposable
{
    private Control _someControl; // implements IDisposable

    public SomeClass()
    {
        _someControl = new RandomControl();
    }

    // ...
}

However, I get the violation in a handler class like this:

public class SomeHandler
{
    private Control _someControl; // implements IDisposable

    public SomeHandler(Control control)
    {
        _someControl = control;
    }

    public void SomeMethod()
    {
        DoSomethingWith(_someControl);
    }

    // ...
}

The handler object is supposed to live exactly as long as the control. Should I really implement IDisposable in this case? In all cases, the handler class should not be responsible for disposing the stored control (but instead the class which created the control in the first place).

Upvotes: 3

Views: 114

Answers (1)

xanatos
xanatos

Reputation: 111860

If you don't have ownership of the "object" you mustn't dispose it.

There are some classes (like StreamReader for example) that have a configuration option to tell if they should take ownership of the Stream you pass them. Clearly StreamReader must be IDisposable and do some logic check

For example: https://msdn.microsoft.com/library/gg712952.aspx

public StreamReader(
    Stream stream,
    Encoding encoding,
    bool detectEncodingFromByteOrderMarks,
    int bufferSize,
    bool leaveOpen
)

Something more similar: the PictureBox class doesn't take ownership of the Image passed. The Image must be disposed by the creator/owner of the control and/or if you replace an Image with another Image, (setting the property Image) by the one that does the operation.

Note that in C# there is no way to know if a control should take/has ownership of something or not. You can only write it in documentation.

Upvotes: 4

Related Questions