Does one need to close both NetworkStream and TcpClient, or just TcpClient?

Ryan Peschel picture Ryan Peschel · Oct 1, 2011 · Viewed 9.9k times · Source

I'm reading the documentation on TcpClient.Close() and noticed this:

Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created.

So, correct me if I'm wrong but this says that if one calls Close() on the TcpClient that the NetworkStream will also be closed.

So then why at the end of the code example are both Close() called?

networkStream.Close();
tcpClient.Close();

Would it be just as fine to only call tcpClient.Close();?

Answer

Ryan Peschel picture Ryan Peschel · Oct 2, 2011

Responding to this question since no one else did so that I may accept an answer.

According to Hans, calling NetworkStream.Close() is unnecessary because TcpClient.Close() closes its underlying NetworkStream.