Simple question - use of unassigned variable error

K

kaiser

Hello

I am trying to get the last lines value in a text file and display it
on screen / read it into a variable.

When I run the following code in a console I get the
following error

"Use of unassigned local variable "LastLine"

What is the problem?



using System;

namespace ConsoleApplication4
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
int counter = 0;
string line;
string LastLine;


System.IO.StreamReader file = new
System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{

Console.WriteLine (line);
LastLine = line;
counter++;
}

file.Close();

Console.WriteLine (LastLine);
Console.ReadLine();



}
}
}
 
G

Guest

Hi kaiser,
the compiler is telling you that it is possible that your code is using a
variable that has never been given a default value, in your case it is the
LastLine variable. This is because you do not initialize the LastLine
variable, then you have a while loop which may never be entered i.e. you do
not give LastLine a value, finally you try to output LastLine to the screen.

The compiler is smart enough to know the while loop may never be entered.
in your code when you declare lastline initialize it as well i.e.

string lastLine = String.Empty;

The compiler will then be happy :)


Hope that helps
Mark R Dawson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top