0

I've made an application that communicates via a second application TCP and I get an error:

System.NullReferenceException: 'Object reference not set to an instance of an object.' --> s was null at the while loop.

This error only occurs when I forcefully close the second application (By pressing the X at the top of the app or killing it via task manager) that is still connected with the first one.

My first application that receives commands and prints them out:

try
{
    StreamReader reader = new StreamReader(client.GetStream());
    StreamWriter writer = new StreamWriter(client.GetStream());
    string s = String.Empty;
    while (!(s = reader.ReadLine()).Equals("PING"))
        Console.WriteLine(s);
    reader.Close();
    writer.Close();
    client.Close();
}
catch (IOException)
{
    Console.WriteLine("woops an error!");
}

My second application that sends the commands:

try
{
    TcpClient client = new TcpClient("192.168.0.107", 8080);
    StreamReader reader = new StreamReader(client.GetStream());
    StreamWriter writer = new StreamWriter(client.GetStream());
    writer.WriteLine("PING");
    writer.Flush();
    reader.Close();
    writer.Close();
    client.Close();
}catch(Exception ex)
    Console.WriteLine(ex.Message);

I tried checking if s==null(like below) and it still throws an exception.

while (!(s = reader.ReadLine()).Equals("PING") || (s==null))
James Z
  • 11,838
  • 10
  • 25
  • 41
William
  • 45
  • 5
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Filburt Jul 27 '17 at 19:00
  • your streamreader depends on your client object, which gets disposed when the second app disconnects, just add in some error handling for it. – colsw Jul 27 '17 at 19:00
  • Your second check `s==null` executed after you call `Equals` method – Aleks Andreev Jul 27 '17 at 19:06

1 Answers1

3

If reader.ReadLine() returns null, null will be assigned to s and then you'll immediately call .Equals on the null (any assignment automatically returns the value that was assigned).. the s == null does nothing to prevent this and indeed it cannot; swapping it to the left wouldn't help either because the brackets take precedence - you need to check it for null before you call .Equals on it

You'd be better off using a for loop and not trying to do so much in one statement

for(s = reader.ReadLine(); s!=null && s.Equals("PING"); s = reader.ReadLine())
Caius Jard
  • 47,616
  • 4
  • 34
  • 62
  • +1 for not trying to do so much in one statement. I think OP ended up creating confusion for his or herself. – KSib Jul 27 '17 at 19:06
  • I am also not a big fan of doing a gazillion things in a single line. It's confusing to yourself and to others who may need to maintain your code. – JuanR Jul 27 '17 at 19:07