1

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
AidanO
  • 868
  • 1
  • 11
  • 33

2 Answers2

4

It is an explicit interface implementation.

It means that only a variable of type IDisposable can call Dispose on this class.

Doing so "hides" the Dispose method when used with a variable of the class type - it will not be able to call it directly without first casting to IDisposable. 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 a Dispose method), this will allow multiple implementations to exist.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • But why it might be a good idea here? Try the **Dispose Pattern** documentation (maybe https://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx just before `#code-snippet-7` , but those links seem to rot faster than the apples from our tree): if the “natural” disposal method name is `Close` (as for a `File`), you want you users doing that, so you ensure they can only use `Dispose` via `IDisposable` – at least that is how I read it: “When doing so, it is important that you make the Close implementation identical to Dispose and _consider implementing the IDisposable.Dispose method explicitly_.” … – PJTraill Nov 02 '16 at 22:22
  • … but I suspect that a lot of explicit implementations of `IDisposable.Dispose()` are misunderstandings or coppy & paced run wild. – PJTraill Nov 02 '16 at 22:25
0

That's an explicit interface implementation. Useful if a class implements several interfaces that have the same methods.

madd0
  • 9,053
  • 3
  • 35
  • 62