Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SqlConnection Object

Status
Not open for further replies.

nooro

Programmer
Feb 7, 2003
22
0
0
GB
Something I was musing over while writing some code. It's not important in the grand scheme, just would help me strip out a single line of code from a few apps ^_^

I have an openDBConnection() function I can call on, creates an SqlConnection, populates the object with my connection string etc. If I open the connection and return that in the function, I can use it fine within the main body of code, that works without a problem and is what I'd ideally want to do. However, it seems to me there is the possibility of an open connection to my DB remaining within the scope of the function. This is absolutely not acceptable for obvious reasons! I would think that the c# garbage collection would tidy this up (close the connection, free up the object) as soon as the function returns? How much can I rely on it? Would it be better simply to open the connection in the main body of code? Is there a better way of going about this?

Comments appreciated ^_^ thanks in advance!
 
>> as soon as the function returns?

what function? your post is ambiguous.

>> Is there a better way of going about this?

you should probably close() your connection as soon as you are done with it, then set your connection object reference to "null". If no other references exist it will be marked for garbage collection. When it gets released back to the connection pool i don't know.

-pete
 
From what I've heard, passing object references back "up" the call chain is a bad idea, unless the object doing the instantiation is specially geared towards being a factory (see
In the case of a GC'd language like C#, yes, the reference will eventually be set to null, but it might take a while. In such cases you should be careful about the lifetime of objects like database connections - be sure to explicitly close your connection, and then call the Dispose method on it to ensure your connection is freed.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top