Reputation: 19
This was frustrating to solve. I kept getting the error "Use of unassigned local variable" on the 'name' variable in the line of code near the end where it outputs to the List Box.
The solution was to initialize the variable 'name'.
At first, I had simply declared the 'name' variable without initializing it. This threw the error of "Use of unassigned local variable". When I finally also initialized that variable (as shown below), the error went away.
But I don't understand this, because, by the time the code reaches that output line, the name variable does get assigned.
Can someone please explain WHY initializing the 'name' variable got rid of the compiling error?
'''
try
{
StreamReader inputFile; // StreamReader object to read the file
string line; // To hold a line from the file.
int row = 0; // Student/line counter.
int column = 0; // Counter for columns in CSV file.
int total = 0; // Accumulator for grades.
double average = 0; // Average test score
string name = ""; // each student's name
// Create delimiter array
// Why is this necessary? Why not just put the delimiter in the Split method call?
//char[] delim = { ',' };
// Open the CSV file
inputFile = File.OpenText("Grades.csv");
while (!inputFile.EndOfStream)
{
// increment the row counter
row++;
// Read a line from the file
line = inputFile.ReadLine();
// Get the test scores as tokens
string[] scores = line.Split(',');
// Set the accumulator to zero
total = 0;
// Calculate the total of the test score tokens
for (column = 0; column < scores.Length; column++)
{
if (column == 0)
{
name = scores[column];
}
else
{
total += int.Parse(scores[column]);
}
}
// Calculate the average test score
average = (double)total / (scores.Length - 1);
// Display the average
//averagesListBox.Items.Add("The average for student " + row + " is " + average.ToString("n1"));
averagesListBox.Items.Add("The average for " + name + " is " + average.ToString("n1"));
}
// Close the file
inputFile.Close();
// Display the total records read
totalLabel.Text = row.ToString("n0");
}
catch (Exception ex)
{
// Display an error message
MessageBox.Show(ex.Message);
}
}
'''
Upvotes: 1
Views: 137
Reputation: 31193
The compiler cannot prove that it does get set anywhere. What if scores.Length
is zero? Then there is no assignment. So the compiler is correct in throwing an error of possible situation where it is not assigned a value.
If you add a condition for scores.Length
always being over zero the compiler might be able to deduce that a value is always set. And you could always set it directly to the first element in an array and loop starting from 1 anyway, which is much more efficient.
Upvotes: 3
Reputation: 886
Actually, it it possible that you're using the name variable without initialization if column < scores.Length
.
That's what the warning is about.
Upvotes: 2