Why is a local variable assigned in one method, but unassigned in a near-identical method?

119 Views Asked by At

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();
    }
3

There are 3 best solutions below

4
On BEST ANSWER

If new StreamWriter(fileName); throws an exception, then s stays unassigned.

Attempt to use it in s.WriteLine(entry); is an error.

And as @DarrenYoung commented, LoadArray returns from catch, so x in x.ReadLine() is guaranteed to be initialized.

0
On

In LoadArray, a caught exception causes the method to return before the reader gets used. In SaveArray, it catches the exception but then continues on its merry way, even though the writer never finished being assigned.

Always remember that a caught exception immediately breaks out of normal control flow, so the current statement will not finish execution.

0
On

Notice how you are declaring a StreamWriter object called writer but you aren't initializing it until you enter your try/catch block. What happens if the try catch fails?

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