none
[C# 3.5] "Use of Unassigned Local Variable" Error When Closing StreamReader Object in Try/Catch/Finally Blocks

    Question

  • I'm wondering of anyone can help me with this problem... In the code below, line 11 always gives a "Use of Unassigned Local Variable" error. Why is this?

    1                 StreamReader SR; // Declared here because of accessibility, not in try
                     // EDIT: Ignore the above indentation. Don't know why it's here...
    2            try 
    3            { 
    4                SR = new StreamReader("DBConfig.cfg"); // Constructer is inside try block 
    5            } 
    6            catch 
    7            { 
    8            } 
    9            finally 
    10            { 
    11                SR.Dispose(); // Error here!! 
    12            } 



    Why am I getting this error? I made sure to declare the StreamReader outside of the try block so that it is accessible to the try, catch, and finally blocks, but I still get some kind of error. Why is this?? Thanks for the help!
    Friday, June 20, 2008 3:39 PM

Answers

  • If the StreamReader constructor throws an exception then SR will be unassigned.

    This pattern is better:

    StreamReader SR = null;
    try
    {
      SR = new StreamReader("");
    }
    finally
    {
      if (SR != null) SR.Dispose();
    }

    This is however much better:

    using (StreamReader SR = new StreamReader(""))
    {
    }

    "using" ensures that Dispose is automatically called, even when an exception happens. 
    Friday, June 20, 2008 4:00 PM

All replies

  • If the StreamReader constructor throws an exception then SR will be unassigned.

    This pattern is better:

    StreamReader SR = null;
    try
    {
      SR = new StreamReader("");
    }
    finally
    {
      if (SR != null) SR.Dispose();
    }

    This is however much better:

    using (StreamReader SR = new StreamReader(""))
    {
    }

    "using" ensures that Dispose is automatically called, even when an exception happens. 
    Friday, June 20, 2008 4:00 PM
  • Thanks for replying! So, in the using block, do I put the try blocks, or does the error handling go on for me somehow?
    Friday, June 20, 2008 4:02 PM
  • Do you have error handling? Looks to me as though you have an empty catch block.

    If you need to catch an exception and handle it, you need to add the try/catch block inside the using clause.

    http://presentationmode.blogspot.com/
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Friday, June 20, 2008 4:05 PM
  • I will... I just started on this yesterday for a project relating to SQL Server, and I decided to redo a bunch of stuff that I'd done before, to make it more efficient, etc.
    Friday, June 20, 2008 4:06 PM