C# – Why calling Dispose() on BinaryReader results in compile error

cnet

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?

Best Answer

It won't work because the Dispose method on BinaryReader has been explicitly implemented.

Instead of being implicitly implemented, as in:

public void Dispose()
{
}

...it has been explicitly implemented, as in:

void IDisposable.Dispose()
{
}

...which means it can only be accessed via the IDisposable interface. Therefore, you have to cast the instance to IDisposable first.

Related Topic