Using statement SqlConnection

Rootbob91

Member
Joined
Jan 21, 2014
Messages
6
Programming Experience
5-10
Hey guys,

I wanted to ask whether the using statement automatically closes the sql.connection, or do you need to call Connection.Close?

I think i read from msdn, that it automatically closes the con.. Is that true?!
 
Yes, that is true. A Using statement creates an object and the corresponding End Using statement disposes it. Closing an open connection is part of the disposal process. The same goes for open Streams and the like.
 
Actually, I should correct something from my previous post. I said that the Using statement creates an object but that's not strictly true. The Using statement actually declares a variable whose scope is the Using block. More often that not, you will create an object and assign it to the variable on that line but you don't have to. You can assign an existing object if you want. Whether it's a new or existing object, it will be disposed at the End Using statement.
 
Another thing to remember is that the IDisposable pattern must be implemented correctly by the developer of the component to ensure all unmanaged resources are disposed of properly. It exists specifically for component developers to have more control over how resources are disposed of, but if implemented incorrectly it can also lead to memory leaks. Obviously that is not the case for CLR code, but the point is the behavior is not a rule, you should always check the documentation to be sure.
 

Latest posts

Back
Top