Say I have the following code:
public static Client Connect(string hostname, int port, bool useSsl)
{
TcpClient tcpClient = new TcpClient(hostname, port);
if (!useSsl)
{
return new Client(tcpClient.GetStream());
}
SslStream sslStream = new SslStream(tcpClient.GetStream());
sslStream.AuthenticateAsClient(hostname);
return new Client(sslStream);
}
When I compile this, Code Analysis says me that I should dispose tcpClient before the reference is out of scope. The problem is that I need to use the underlying stream instance further and I can’t dispose the tcpClient here. Simultaneously, I don’t want to store a reference to the tcpClient somewhere in order to dispose later as I need the stream only. What is the right solution here? Thanks.
1 Answer