0

I want to declare a MySqlDataReader, without initialising it or assigning any value to it. Like the code below.

MySqlDataReader rdr;

try
{ /* stuff to open the MySqlDataReader and use it, not important for my question */ }
catch (Exception e)
{ /* error handling stuff, not important for my question */ }
finally
{
    /* code to close the reader when things have gone wrong */
    try
    {
        if (rdr != null)
        {
            if (rdr.IsClosed == false)
            {
                rdr.Close();
            }
        }
    }
    catch (Exception e)
    { /* error handling stuff, not important for my question */ }
}

The reason for that is I want to close the MySqlDataReader in a finally section of the try if it does in fact I do get a run time error. So the MySqlDataReader has to be declared before of the try, otherwise it'll be out of scope for the finally code.

However when I compile the code above I get the compile time error "Use of unassigned local variable 'rdr'" so I want to set it to something for example

MySqlDataReader rdr = New MySqlDataReader();

But this give me a compile time error "The type 'MySql.Data.MySqlClient.MySqlDataReader' has no constructors defined". And assigning the result of a command object will make the code compile however that can go wrong and is what my try is trying to catch.

When this function is called for a second time if the MySqlDataReader object is not closed from the first iteration, then it will crash second time around.

So how do I clean up my MySqlDataReader objects when things go wrong?

user1644564
  • 385
  • 3
  • 11

2 Answers2

2

Just assign it with null. The compiler will know a value has assigned, although it is null.

MySqlDataReader rdr = null;

In your finally block, check on the null value.

MySqlDataReader rdr = null;

try
{
    ... // do stuff here
}
finally
{
    if (rdr != null)
    {
        // cleanup
    }
}

Or use using if possible. It will cleanup rdr for you:

using (MySqlDataReader rdr = ... )
{
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

One option is to initialize it to null to start with:

MySqlDataReader rdr = null;

After all, you're already checking whether it's null within the finally block in your sample code, so that's fine.

It's not clear why you're not just using a using statement though. You can always put a try/catch inside (or outside) that.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194