I was just tidying up some code when I found this region in the class:
#region IDisposable Members
void IDisposable.Dispose()
{
}
#endregion
Now understand that this is implementing the Dispose method for the IDisposable interface and I know that the class declaration says that this class will implement the IDisposable interface.
What I don’t get is why it reads:
void IDisposable.Dispose()
And not:
public void Dispose()
I guess that the IDisposable.Dispose indicated explicitly that this is the Dispose that implements the IDisposable interface? Is this correct and what’s the advantage of doing this?
It is an explicit interface implementation.
It means that only a variable of type
IDisposablecan callDisposeon this class.Doing so “hides” the
Disposemethod when used with a variable of the class type – it will not be able to call it directly without first casting toIDisposable. It is possible that the implementer did this on purpose.Additionally, if the class were to implement its own
Dispose(or inherit/implement from a class/interface that also defines aDisposemethod), this will allow multiple implementations to exist.