2

In following sinppet of code, I would like to ask: How does the author evaluates the variable 'line' in the while loop before he initialize it with a value?

StreamReader myReader = new StremReader("Values.txt");

string line = "";

while (**line != null**)

{

    line = myReader.ReadLine();
    if (line != null)
        console.WriteLine(line);
}

myReader.Close();

console.ReadLine();
1
  • hmm the variable is initalized? An empty string is not the same as a null reference Commented Oct 1, 2012 at 23:14

3 Answers 3

4

It is initialized with a value: the empty string:

string line = "";

Even if it didn't have a value and was null, it's still possible to test whether it is null with a comparison like in that while loop.

Now, this is what an uninitialized variable looks like:

string line; // Help! I'm only declared!
while (line != null)
{
    // do stuff
}

Trying to compile that would give you this error: "Use of unassigned local variable 'line'". But assigning any value, including "" or null would make things right again.

Sign up to request clarification or add additional context in comments.

Comments

1

A quick and easy to read way:

string line;
while((line = myReader.ReadLine()) != null)
{
   Console.WriteLine(line);
}

As for the author's snippet of code you provided, line is initialized to an empty string. Because of this, it always will go into the while loop at least one time. Then it grabs a line from the reader, does stuff with it if it isn't null, and moves on. I would never write it like that, as you are doing too many checks that way. Might as well do a single assignment & check in one line.

Comments

0

Short Answer: line variable is already initialized with empty string "".

Regarding the given example of code, i would suggest to use using construct to ensure that un-managed code is disposed asap.

using (StreamReader myReader = new StreamReader("Values.txt"))
            {
                string line = "";
                while (line != null)
                {

                    line = myReader.ReadLine();
                    if (line != null)
                        console.WriteLine(line);
                }

                //myReader.Close();
                console.ReadLine();
            };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.