1

Socket.Dispose() is an inaccessible member. However, we can bypass this by doing the following:

((IDisposible)Socket).Dispose()

Two questions:

  1. Why is this allowed?
  2. How does this work internally?
GEOCHET
  • 21,119
  • 15
  • 74
  • 98

2 Answers2

5

I believe this feature is "explicit interface implementation." Using this will only allow the implemented methods to be called if the object is explicitly cast to the interface.

Here's a tutorial on this:

http://msdn.microsoft.com/en-us/library/aa288461(VS.71).aspx

Andy White
  • 86,444
  • 48
  • 176
  • 211
  • Check out this post: http://stackoverflow.com/questions/280495/why-to-use-explicit-interface-implementation-to-invoke-a-protected-method – Andy White Apr 02 '09 at 02:22
  • I'm not sure I understand. It means that Socket implements IDisposable, but for some reason the designers didn't want the "Dispose()" method on the "public API" of the class. In order to use Dispose, you must cast the Socket to IDisposable – Andy White Apr 02 '09 at 02:26
  • @Sasha, Socket has a Close method which calls Dispose behind-the-scenes. The designers of the Socket class are basically saying "although this class implements IDisposable, we'd prefer that you call Close rather than Dispose". – LukeH Apr 02 '09 at 12:14
3

Whenever a class implements a method such as Close() which accomplishes the same work as Dispose(), then it is recommended to explicitly implement the IDisposable interface, so that a developer will typically only see the Close() method, yet the Dispose method is still accessible through the IDisposable interface for use by the framework where a Dispose method is expected.

Sometimes it makes sense to essentially expose Dispose under a different name, such as Close, where it makes for more readable code. You see these throughout the .NET Framework with things that can be "Closed" such as file handles and connections.

Edit: See http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756

AaronLS
  • 37,329
  • 20
  • 143
  • 202
  • It is in the book called .NET Framework Design Guidelines, written by the same people who wrote the .NET Framework. – AaronLS Apr 02 '09 at 17:43