15

Just as the title says:

How can TcpClient implement IDisposable and not have a public Dispose method?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
CannibalSmith
  • 4,742
  • 10
  • 44
  • 52
  • 1
    When I'm riding intellisense to get a feel for an unfamiliar interface (probably bad, I know), this is one of my pet frustrations because there's little indication that a using statement would be appropriate. – spender Feb 24 '10 at 11:32
  • Speaking of `using`, I've never encountered a local disposable variable in my life. All my disposables are members. So I'm puzzled by all the `using` rage. – CannibalSmith Feb 24 '10 at 11:39
  • @CannibalSmith: `using` is a _replacement_ for keeping them as members, for things that are really only relevant in the `using` area. One of its uses is opening a database or network connection, performing the operations you need to do, and then closing it automatically. – Nyerguds May 03 '13 at 09:56

2 Answers2

11

By using explicit interface implementation. Instead of

public void Dispose()
{
    ...
}

it would have

void IDisposable.Dispose()
{
    ...
}

Various other types do this; sometimes it's out of necessity (e.g. supporting IEnumerable.GetEnumerator and IEnumerable<T>.GetEnumerator) and at other times it's to expose a more appropriate API when the concrete type is known.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Then in this case what's the recommended way to properly dispose of it? By calling the Dispose() method by explicitly casting it to IDisposable, or by calling TcpClient.Close()? – KFL May 25 '16 at 21:50
  • 1
    @KFL: You can just use a `using` statement - that's normally the best option. If you can't use a `using` statement, calling `Close` is fine. – Jon Skeet May 25 '16 at 21:54
3

See explicit interface implementation. You need to explicitly cast the instance of TcpClient to IDisposable, or wrap it in a using() {...} block. Note that classes that implement IDisposable explicitly often provide a public Close() method instead

thecoop
  • 45,220
  • 19
  • 132
  • 189