Search code examples
c#tcpclient

Getting exception while reading Connected property on TcpClient instance


public bool IsConnected
{
    get { return _tcpClient == null ? false : _tcpClient.Connected; }
}

throws a

"Object reference not set to an instance of an object."

at

at System.Net.Sockets.TcpClient.get_Connected() at Project.ViewModel.ModbusOutputCounter.get_IsConnected() in C:...\ModbusOutputCounter.cs:line 115

How is this possible, and how can we prevent receiving this exception?

Edit:

as per svk's anwer the problem was in Disposing, which is internally called in Close() method. A workaround:

return _tcpClient?.Client != null ? _tcpClient.Connected : false;

Solution

  • According to reference source for TcpClient, Connected directly returns Connected of the underlying socket. This means that Connected will throw NullReferenceException when the socket is null. Though skimming the reference source, I found two cases when that can happen:

    1. When the TcpClient has been Disposed.
    2. When you explicitly set the Client Socket to null.