Search code examples
c#.netasp.netasp.net-mvcidisposable

Should we implement IDisposable if one member is IDisposable?


I think so. But take a look at a built-in class in ASP.NET:

public sealed class HttpPostedFile
{
    public Stream InputStream { get; }   // Stream implements IDisposable
    // other properties and methods
}

Suppose I have an instance of HttpPostedFile called file. Since there is no Dispose method to explicitly invoke, file.InputStream.Dispose() won't be invoked until it's destructed, which I think goes against the original intention of IDisposable. I think the correct implementation should contain a standard IDisposable implementation. So, if one of the members implements IDisposable, the class needs to implement it too.

What are your opinions? It seems to be a bit complicated.


Solution

  • In general, you should implement IDisposable if you own the resource represented by the property - see this question for a discussion on this subject.

    I'd say that because HttpPostedFile is instantiated during processing of an HTTP request, it doesn't own the stream, and hence doesn't dispose it. The stream will be disposed when the HTTP request processing finishes.