views:

713

answers:

3

If I use something like:

using (OdbcConnection conn = new OdbcConnection(....))
{
  conn.open();
  my commands and sql, etc.
}

Do I have to do a conn.close(); or does the using statement keep me from doing that last call? Does it dispose of everything in the using block? For example, if I called other objects unlrelated would it dipose of those automatically also?

Thank you. I was unclear after reading about using on Microsoft's site. I want to make sure I don't have any memory leaks.

+4  A: 

The using statement will handle calling the Close and Dispose methods for you.

Scott Hanselman has a pretty good explanation of the using statement.

Notorious2tall
+5  A: 
  1. The using block will dispose of the OdbcConnection.
  2. Normal scope rules work for anything declared inside the using block.
  3. The using block will not clean up any other IDisposable objects. It only cleans up the declared item
    • note that you can nest using blocks, or if the items are the same type, multiple items can be initialized at the same time.

See the top bit of my other answer for How do I use the using keyword in C# for a little more information.

I should also mention that you can close (dispose) of the connection as soon as you are done with it to release the resource. The guidelines say that the caller should be able to repeatedly call the dispose method. The using block is essentially just a safety net and allows writing clearer code in most circumstances.


[Edit] e.g. multiple initialization in a using: initialize more than one object in the same using without having to nest using blocks if the objects are the same type:

using (Bitmap b1 = new Bitmap("file1"), b2 = new Bitmap("file2")) 
{ ... }

Joel Coehoorn mentioned stacking, which is nesting but omitting the braces, much as you can omit the braces in a for, or if statement. The UI doesn't reformat with an indent. I'd be curious what the IL looks like.

using(Bitmap b = new Bitmap("filex"))
using(Graphics g = Graphics.FromImage(b))
{ 
}

It is an error to use put different objects in the same using error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement.

// error CS1044
using(Bitmap b = new Bitmap("filex"), Graphics g = Graphics.FromImage(b))
Robert Paulson
They don't even have to be the same type: you can "stack" multiple using statments together (creating both an connection and command object at the same level, for example) to avoid creating deeply-nested scopes.
Joel Coehoorn
I have some code with an example here:http://stackoverflow.com/questions/436026/how-to-improve-data-access-layer-select-method-pattern
Joel Coehoorn
+1  A: 

The using statement ensures that an object which implements IDisposable gets disposed. It will only dispose the object that is referened in the using block so your code is basically equivlant to:

OdbcConnection conn = new ....;
try
{
   conn.open();
   conn.....
}
finally
{
   conn.dispose();
}
JoshBerke