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;
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:
TcpClient
has been Dispose
d.Client
Socket
to null
.