Search code examples
c#.netunmanagedidisposablemediainfo

Which class "owns" an unmanaged resource (and which implements IDisposable)?


I'm working on an OSS project to make the popular MediaInfo library easier to use in .NET, but this question is generalizable.

If a derived class D always instantiates an object O when calling its base class DB's constructor. DB sets its value to that sent to its constructor, but the value itself is declared in DB's base class B:

  1. Who "owns" O (AKA mediaInfo in the code below)?
  2. In the case of a .NET application, which of these should implement IDisposable? Note: O is unmanaged, or at least is an instantiation of a managed object wrapped around an unmanaged library, but does need cleanup in the form of "MediaInfo.Close();". I am not certain this counts as "unmanaged."

To help clarify, let me use actual code:

D derives from DB:

// MediaFile is "D" 
public sealed class MediaFile : GeneralStream
{
    public MediaFile(string filePath)
        : base(new MediaInfo(), 0) {
        // mediaInfo is "O"
        mediaInfo.Open(filePath);
    }
}

DB sets its inherited O, derived from B:

// GeneralStream is "DB"
public abstract class GeneralStream : StreamBaseClass
{
    public GeneralStream(MediaInfo mediaInfo, int id) {
        this.mediaInfo = mediaInfo; // declared in StreamBaseClass
        // ...
    }
}

B declares O:

// StreamBaseClass is "B"
public abstract class StreamBaseClass
{
    protected MediaInfo mediaInfo; // "O" is declared
    // ...
}

Solution

  • The object, which holds a reference to the resource, owns it.

    StreamBaseClass has the reference mediaInfo and should implement IDisposable. The reference and the Dispose method will automatically be inherited by the deriving classes.