declaring a MySqlDataReader without initialising it

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?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow