Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Go Back   Wrox Programmer Forums > C# and C > C# 1.0 > C#
Password Reminder
Register
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
C# Programming questions specific to the Microsoft C# language. See also the forum Beginning Visual C# to discuss that specific Wrox book and code.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C# section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old July 15th, 2003, 07:06 PM
Registered User
 
Join Date: Jul 2003
Location: , WA, USA.
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default variable initialization with try..finally

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?
Reply With Quote
  #2 (permalink)  
Old July 15th, 2003, 07:11 PM
Registered User
 
Join Date: Jul 2003
Location: , WA, USA.
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Oops - just to avoid confusion, my previous example should have been
if (dr != null)
in the finally block. It was intended to check whether the variable had been initialized.

Reply With Quote
  #3 (permalink)  
Old July 16th, 2003, 06:56 AM
Authorized User
 
Join Date: Jun 2003
Location: Gainesville, FL, USA.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hmm... how about using
SqlDataReader dr = null;
as your declaration + initialization to null?
Then the check
if(dr!=null)
should work fine

HTH,
Olorin
Reply With Quote
  #4 (permalink)  
Old July 16th, 2003, 09:57 AM
Friend of Wrox
 
Join Date: Jun 2003
Location: Wien, Wien, Austria.
Posts: 158
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via ICQ to NotNowJohn
Default

Hi there,
In C# you can use a keyword "using while the object's declaration and initialization. This keyword tell the compiler to call object's Dispose method when he leave the scope you defined (if you forgot to call it). In other words use this statement:
Code:
using (SqlDataReader dr=command.ExecuteReader())
{
//some code block
}
At this point Dispose() method will be called. You can test this if you try to declare and initialize new SqlDataReader object, although you have not closed the previous reader object.

...but the Soon is eclipsed by the Moon
Reply With Quote
  #5 (permalink)  
Old July 16th, 2003, 04:52 PM
Authorized User
 
Join Date: Jun 2003
Location: Gainesville, FL, USA.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Quote:
quote:
At this point Dispose() method will be called. You can test this if you try to declare and initialize new SqlDataReader object, although you have not closed the previous reader object.
NotNowJohn,
correct me if I'm wrong, but wouldn't this be equivalent to simply NOT call the .Close() method on the SqlDataReader ?

And, if so, wouldn't this potentially lead to problems (after all, if not calling .Close() will not raise problems, why are we worrying about it in the first place?)

I'm curious.

Thanks,
Olorin
Reply With Quote
  #6 (permalink)  
Old July 16th, 2003, 08:30 PM
Registered User
 
Join Date: Jul 2003
Location: , WA, USA.
Posts: 6
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Olorin - explicitly initializing to null did the trick perfectly. Thanks!

Reply With Quote
  #7 (permalink)  
Old July 17th, 2003, 04:04 AM
Friend of Wrox
 
Join Date: Jun 2003
Location: Wien, Wien, Austria.
Posts: 158
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via ICQ to NotNowJohn
Default

Olorin,
Of course that is strongly recommended to release all resources after using as soon as possible, and Close() methods for those objects working with resources are required. I mentioned using (...) feature *only* if you think that is possible to forget to release used resource. I use sometimes both, using kwd and exception handling blocks.
Well, I am not sure about the DataReader's IDisposable implementation but I suppose that Dispose() method has a pointer to DataReader instance and in the body of method checks DataReader state, close it if it's opened and proceed to GC to release used memory.

Regards,

...but the Soon is eclipsed by the Moon
Reply With Quote
  #8 (permalink)  
Old July 17th, 2003, 06:47 AM
Authorized User
 
Join Date: Jun 2003
Location: Gainesville, FL, USA.
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
Default

guppyheart,
glad to hear it worked.

NotNowJohn,
agreed; thanks for the clarification :-)

Cheers,
Olorin
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Try/Finally to prevent connection pooling leak spinout ASP.NET 2.0 Basics 4 June 19th, 2007 08:48 AM
Declaration of variable without initialization v_kewlani Other Programming Languages 0 May 24th, 2007 01:51 AM
Try/Catch/Finally rohit.sharma C# 2 January 12th, 2007 11:44 PM
variable initialization vin_0x1 Classic ASP Databases 1 April 18th, 2006 06:46 AM
initialization vin_0x1 Classic ASP Professional 3 April 16th, 2006 06:40 AM



All times are GMT -4. The time now is 05:33 PM.


Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.