"Chris" <Ch***@discussi ons.microsoft.c om> wrote in message
news:FF******** *************** ***********@mic rosoft.com...
Hi,
I am using the try catch finally block in many places in my code.
When a create an sqldatareader dr and try to close it in my
finally block I get the error: use of unsigned local variable.
dr.close();
works fine in the try but not in the finally.
How can I access my local objects in the finally without these errors?
Hi Chris,
In addition to the excellent answers given so far, there is another
construct of C# that you may not be aware of.
You are clearly being a good citizen and cleaning up the data reader during
error handling. However, C# has a pretty nice construct that will call the
..Dispose method for you... it is called 'using'
I snatched a bad example of using the Data Reader object from a random site
and rewrote it to use the 'using' statement, here:
SqlDataReader data;
using (data = command.Execute Reader(CommandB ehavior.CloseCo nnection))
{
while( data.Read() )
{
Console.WriteLi ne("Company Name " +
data.GetString( data.GetOrdinal ("CompanyName") );
}
} // automatically calls data.Dispose();
Here is the spec page in the MSDN. It's a very cool capability of the
language, and reduces your code brilliantly.
Note: you still need a try-catch-finally, but you won't need to close the
data reader, because leaving that block of 'using' code, FOR ANY REASON,
will call Dispose for you.
http://msdn.microsoft.com/library/de...pspec_8_13.asp
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--