tags:

views:

295

answers:

2

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?
+5  A: 

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
yea.... makes sense, what is the behind this for Socket, for example? thx
Check out this post: http://stackoverflow.com/questions/280495/why-to-use-explicit-interface-implementation-to-invoke-a-protected-method
Andy White
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
@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
+3  A: 

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
+1, But do you have a reference for this recommendation? Or an example of a newer class? System.IO.Stream has both Dispose and Close
Henk Holterman
It is in the book called .NET Framework Design Guidelines, written by the same people who wrote the .NET Framework.
AaronLS