William
William

Reputation: 45

Object reference not set c#

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))

Upvotes: 0

Views: 555

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

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())

Upvotes: 3

Related Questions