473,387 Members | 1,456 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Using

Hi

I have some code in C# for accessing a database. For example:

using (SqlConnection conn = GetConnection() )
{
using (SqlCommand command = new SqlCommand( ...
{
...
}
}

(The function GetConnection just delivers the appropriate connection object,
and of course there is a lot of code snipped).

My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)

Thanks,
Peter
Nov 17 '05 #1
4 2215
Yes, that is correct

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Hi

I have some code in C# for accessing a database. For example:

using (SqlConnection conn = GetConnection() )
{
using (SqlCommand command = new SqlCommand( ...
{
...
}
}

(The function GetConnection just delivers the appropriate connection object,
and of course there is a lot of code snipped).

My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)

Thanks,
Peter

[microsoft.public.dotnet.languages.csharp]
Nov 17 '05 #2
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:O6**************@tk2msftngp13.phx.gbl...
My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)

Thanks,
Peter


Yes, Peter. The using keyword is a shorthand for a try finally block which
calls Dispose. Dispose will call Close.

Hence, the connection will be closed even if your code throws an exception.

Better yet, you don't need nested using-statements for each sql-object. The
sql client classes are pretty smart.
If you create a connection in using block, create a command, hook it to your
connection and then perhaps call ExecuteReader you don't need to dispose all
those objects. The SqlConnection will not only dispose itself but the
command and the reader as well.

Hence, one using statement would be sufficient.

Happy Coding
- Michael S
Nov 17 '05 #3
KH
Although it's not a bad idea to explicitly close the other objects - command,
reader, or whatever.

Also you might get better performance by only calling Close vs. Dispose,
especially if your app has a lot of interaction with the database -
SqlConnection may reuse the connection - calling Dispose definatly kills the
connection and destroy's the object, meaning that a new one must be created
each time.
"Michael S" wrote:
"Peter Kirk" <pk@alpha-solutions.dk> wrote in message
news:O6**************@tk2msftngp13.phx.gbl...
My question concerns the "using" statement. I just want to be sure that my
understanding is correct: it is not necessary for me to explicitly close
these database resources because the using statement ensures that these
objects have a Dispose function which is called, and these take care of
cleaning up? (Even if an exception is thrown?)

Thanks,
Peter


Yes, Peter. The using keyword is a shorthand for a try finally block which
calls Dispose. Dispose will call Close.

Hence, the connection will be closed even if your code throws an exception.

Better yet, you don't need nested using-statements for each sql-object. The
sql client classes are pretty smart.
If you create a connection in using block, create a command, hook it to your
connection and then perhaps call ExecuteReader you don't need to dispose all
those objects. The SqlConnection will not only dispose itself but the
command and the reader as well.

Hence, one using statement would be sufficient.

Happy Coding
- Michael S

Nov 17 '05 #4
Why oh why oh why does this myth persist.

Here is the code for SqlConnection.Dispose reverse engineered via Reflector
protected override void Dispose(bool disposing)
{
if (disposing)
{
switch (this._objectState)
{
case ConnectionState.Open:
{
this.Close();
break;
}
}
this._constr = null;
}
base.Dispose(disposing);
}

In other words, if the connection is open it closes it, then it nulls out the connection string. All this means is you can't call
Open on that instance without reseting the connection string. The underlying connection just returns to the pool as with Close.

Whoever started the rumour that the connection is somehow removed from the pool / permanently closed or
whatever has alot to answer for.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
Although it's not a bad idea to explicitly close the other objects - command,
reader, or whatever.

Also you might get better performance by only calling Close vs. Dispose,
especially if your app has a lot of interaction with the database -
SqlConnection may reuse the connection - calling Dispose definatly kills the
connection and destroy's the object, meaning that a new one must be created
each time.

Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Enos Meroka | last post by:
Hallo, I am a student doing my project in the university.. I have been trying to compile the program using HP -UX aCC compiler, however I keep on getting the following errors. ...
3
by: Mike L | last post by:
Should the command call "using" be before or after my namespace? **AFTER** namespace DataGridBrowser { using System; using System.Drawing; using System.Drawing.Drawing2D; using...
3
by: xzzy | last post by:
I was wondering why we have to have using System.Data using System.Configuration using etc.... why are they not all lumped into one 'using'? In other words, is there a best way to use...
14
by: pmud | last post by:
Hi, I need to use an Excel Sheet in ASP.NET application so that the users can enter (copy, paste ) large number of rows in this Excel Sheet. Also, Whatever the USER ENETRS needs to go to the...
8
by: acb | last post by:
Hi, I wrote a DLL Component (using Visual Studio 2005) and managed to include it into a C# Console application. I am now trying to include this component into a Web project. I copy the DLL...
0
by: Metal2You | last post by:
I'm working on an ASP.NET 2.0 application in Visual Studio 2005 that accesses a Sybase database back end. We're using Sybase SQL Anywhere 9.0.2.3228. I have installed and registered the Sybase...
10
by: mg | last post by:
I'm migrating from VB6 and have a question about using 'Using' and the best way to use it. Here is a example of a small bit of code: dbConx("open") Using CN Dim CMD As New OleDbCommand(sSQL,...
0
by: Eugene Anthony | last post by:
The problem with my coding is that despite removing the records stored in the array list, the rptPages repeater control is still visible. The rptPages repeater control displayes the navigation...
3
by: JDeats | last post by:
I have some .NET 1.1 code that utilizes this technique for encrypting and decrypting a file. http://support.microsoft.com/kb/307010 In .NET 2.0 this approach is not fully supported (a .NET 2.0...
6
by: =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post by:
Greetings! I was researching AJAX to provide a solution to displaying status messages while a long process executed. I found several examples online and was able to use their code to get a quick...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.