I'm moving into C# from
VB.Net, and I've hit a snag with uninitialized variables. I deal with lots of functions that retrieve data using a SqlDataReader and then do things with the data. After I'm finished, I want to make sure I close the datareader whether an error was encountered or not. What's the proper way to handle that when I'm using a try..catch..finally structure?
This is the structure I had been using, but it gives an error in C#:
SqlDataReader dr; //there is no new() initialization for this object
try
{
//do some stuff to make a database connection and command object
dr = sqlcmd.ExecuteReader(myQuery);
//do some more stuff to use the data from the datareader
}
catch (Exception err)
{
//do error handling
}
finally
{
if (dr == null) //throws unassigned local variable error
{
if (dr.IsClosed == false) { dr.Close(); }
}
}
How can I make sure that, no matter where an error might happen, I don't leave an open datareader? I obviously can't close it before I've used the data, but if an error happens while I'm trying to use the data, neither the catch nor the finally blocks seem to be able to access and close the dr object. I suppose I could do nested try blocks, but I'd rather not if I don't have to - makes for messier code and repetition of the same error-handling. Is there another way?