I have the following class which uses BinaryReader internally and implements IDisposable.
class DisposableClass : IDisposable { private BinaryReader reader; public DisposableClass(Stream stream) { reader = new BinaryReader(stream); } protected virtual void Dispose(bool disposing) { if (disposing) { ((IDisposable)reader).Dispose(); // reader.Dispose();// this won't compile } } public void Dispose() { this.Dispose(true); } }
I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don’t understand why I can’t just call the Dispose() method directly without casting to IDisposable?
It won’t work because the
Disposemethod onBinaryReaderhas been explicitly implemented.Instead of being implicitly implemented, as in:
…it has been explicitly implemented, as in:
…which means it can only be accessed via the
IDisposableinterface. Therefore, you have to cast the instance toIDisposablefirst.