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:
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
// ...
}
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.