When I compile this code, I receive a compilation error saying writer
is an unassigned local variable in SaveArray
. It doesn't complain about reader
in the similar method LoadArray
. Why is this the case? Shouldn't they behave the same?
static void SaveArray(string fileName, string[,] arr)
{
StreamWriter writer;
try
{
writer = new StreamWriter(fileName);
}
catch
{
MessageBox.Show("Error, could not open " + fileName + " for saving");
}
try
{
foreach (string entry in playerArray)
{
writer.WriteLine(entry);
}
}
catch
{
MessageBox.Show("Couldn't save");
}
writer.Close();
}
static void LoadArray(string fileName, string[,] arr)
{
StreamReader reader;
try
{
reader = new StreamReader( fileName );
}
catch
{
MessageBox.Show("Error when reading file" +fileName);
return;
}
try
{
for(int i=0; i<=arr.GetUpperBound(0); ++i)
{
for (int j = 0; j<=arr.GetUpperBound(1); ++j)
{
arr[i, j] = reader.ReadLine();
}
}
}
catch
{
MessageBox.Show("Could not read from file " +fileName);
}
reader.Close();
}
If
new StreamWriter(fileName);
throws an exception, thens
stays unassigned.Attempt to use it in
s.WriteLine(entry);
is an error.And as @DarrenYoung commented,
LoadArray
returns fromcatch
, sox
inx.ReadLine()
is guaranteed to be initialized.