Search code examples
c#sockets

Does TcpClient.Dispose() closes the TcpClient.GetStream?


For closing a TcpClient it's necessary to close the stream. And the usual way of doing that is:

        client.GetStream().Close();
        client.Close();

so using client.Close() by itself is not enough, my question is does the client.Dispose() works same as client.GetStream().Close() so the closing will be like

        client.Dispose();
        client.Close();

this is what i understood from reading the TcpClient reference source as the Dispose method closes the stream, so am i correct or am i missing something? Thank you in advanced.


Solution

  • Close calls Dispose, Dispose disposes the stream:

    IDisposable dataStream = m_DataStream;
    if (dataStream != null)
    {
        dataStream.Dispose();
    }
    

    You don't need to call both Close and Dispose. Choose one.

    You can check the source code

    It's quite common for IDisposable classes to have another method doing the same as Dispose, but with a different, domain-specific name. Very often IDisposable.Dispose is implemented explicitly, so that it can be used by using statement or after a cast, but doesn't clutter the class' interface.