473,387 Members | 1,619 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.

what's the point of the 'using' construct?

I have only ever seen this used like this :

try
{
using (SqlConnection conn = new SqlConnection())
{
//db stuff
}
catch
{
}

What advantage do you get from using this? And are there any other uses
for this?

*** Sent via Developersdex http://www.developersdex.com ***
Jul 6 '06 #1
9 1437
Mel
Using closes the connection and frees the resource.
"Mike P" <mi*******@gmail.comwrote in message
news:e9**************@TK2MSFTNGP03.phx.gbl...
>I have only ever seen this used like this :

try
{
using (SqlConnection conn = new SqlConnection())
{
//db stuff
}
catch
{
}

What advantage do you get from using this? And are there any other uses
for this?

*** Sent via Developersdex http://www.developersdex.com ***

Jul 6 '06 #2
Mike,

Well, "using" in general is used to make sure that instances that
implement IDisposable are always called when the code block is exited.

The reason people wrap try/catch blocks around the using statement is to
catch an exception if the block is exited as the result of an exception
being thrown.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Mike P" <mi*******@gmail.comwrote in message
news:e9**************@TK2MSFTNGP03.phx.gbl...
>I have only ever seen this used like this :

try
{
using (SqlConnection conn = new SqlConnection())
{
//db stuff
}
catch
{
}

What advantage do you get from using this? And are there any other uses
for this?

*** Sent via Developersdex http://www.developersdex.com ***

Jul 6 '06 #3
Hello Mike,

Read this http://msdn2.microsoft.com/en-us/library/yh598w02.aspx

MPI have only ever seen this used like this :
MP>
MPtry
MP{
MPusing (SqlConnection conn = new SqlConnection())
MP{
MP//db stuff
MP}
MPcatch
MP{
MP}
MPWhat advantage do you get from using this? And are there any other
MPuses for this?

---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Jul 6 '06 #4
The main advantage is that Dispose is called on the target as soon as the
closing brace is reached. That in itself is a good thing.
Peter

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"Mike P" wrote:
I have only ever seen this used like this :

try
{
using (SqlConnection conn = new SqlConnection())
{
//db stuff
}
catch
{
}

What advantage do you get from using this? And are there any other uses
for this?

*** Sent via Developersdex http://www.developersdex.com ***
Jul 6 '06 #5
Mike,

The "using" statement has two benefits; makes your code simpler, and more
efficient.

When you use the "using" statement, the compiler puts any code inside the
brackets inside a TRY/FINALLY block, and inside the FINALLY block it calls
the DISPOSE method (which means you can only use it with classes that
implement IDisposable).

This has the advantage of you not having to code calls to the Close or
Dispose method, which if you get it wrong could cause an
ObjectDisposedException to be thrown, AND it allows the CLR/Garbage Collector
to collect it sooner in most cases.

HTH

Gandalf
MCSD.NET, MCAD, MCT
"Mike P" wrote:
I have only ever seen this used like this :

try
{
using (SqlConnection conn = new SqlConnection())
{
//db stuff
}
catch
{
}

What advantage do you get from using this? And are there any other uses
for this?

*** Sent via Developersdex http://www.developersdex.com ***
Jul 6 '06 #6
Mel wrote:
Using closes the connection and frees the resource.
No, using guarantees that Dispose is called once the using block is exited.
In the case of an SqlConnection, its dispose also closes the connection if
it is open, but "using" does not do that. The GC will free the resource at
some later time.
--
Tom Porterfield

Jul 6 '06 #7
Many thanks for the explanations guys!

Cheers,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Jul 7 '06 #8
So in my Data Access layer I am now using the using contruct like this
below. Is it correct to put my try catch block, and my return statement
inside the using block or should they be outside it?

public DBResult AddCompetitorMachine(int intCompetitor, string
strMachine)
{
using (SqlConnection objConnection = new
SqlConnection(ConfigurationManager.ConnectionStrin gs["ConnectionString"]
..ConnectionString))
{
DBResult dbrAddMachine;

SqlCommand objCommand = new
SqlCommand("AddCompetitorMachine", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;

SqlParameter prmCompetitor = new SqlParameter("@Competitor",
SqlDbType.Int, 4);
prmCompetitor.Value = intCompetitor;
objCommand.Parameters.Add(prmCompetitor);

SqlParameter prmMachine = new SqlParameter("@Machine",
SqlDbType.VarChar, 50);
prmMachine.Value = strMachine;
objCommand.Parameters.Add(prmMachine);

SqlParameter prmCompetitorMachineID = new
SqlParameter("@CompetitorMachineID", SqlDbType.Int, 4);
prmCompetitorMachineID.Direction =
ParameterDirection.Output;
objCommand.Parameters.Add(prmCompetitorMachineID);

try
{
objConnection.Open();
objCommand.ExecuteNonQuery();

if (prmCompetitorMachineID.Value != System.DBNull.Value)
{
dbrAddMachine = DBResult.OK;
}
else
{
dbrAddMachine = DBResult.Error;
}
}
catch
{
dbrAddMachine = DBResult.Error;
}

return dbrAddMachine;
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Jul 7 '06 #9
Mike P wrote:
So in my Data Access layer I am now using the using contruct like this
below. Is it correct to put my try catch block, and my return statement
inside the using block or should they be outside it?
It is fine to put those inside the using block.
--
Tom Porterfield
Jul 7 '06 #10

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

Similar topics

4
by: Ruud de Jong | last post by:
The question I have is: how safe / future proof / portable is the use of the __subclasses__ method that exists for new-style classes? Background: I thought I had found an easy-to-understand...
7
by: Jonathan Fine | last post by:
Giudo has suggested adding optional static typing to Python. (I hope suggested is the correct word.) http://www.artima.com/weblogs/viewpost.jsp?thread=85551 An example of the syntax he proposes...
12
by: Steven T. Hatton | last post by:
This is something I've been looking at because it is central to a currently broken part of the KDevelop new application wizard. I'm not complaining about it being broken, It's a CVS images. ...
121
by: typingcat | last post by:
First of all, I'm an Asian and I need to input Japanese, Korean and so on. I've tried many PHP IDEs today, but almost non of them supported Unicode (UTF-8) file. I've found that the only Unicode...
13
by: Jason Huang | last post by:
Hi, Would someone explain the following coding more detail for me? What's the ( ) for? CurrentText = (TextBox)e.Item.Cells.Controls; Thanks. Jason
17
by: Mike Hofer | last post by:
While I'd toyed with C, C++, and Java over the last 20 years or so, my principal language has been BASIC, QBASIC, then Visual Basic, and finally Visual Basic .NET. But lately, I've been using C#...
669
by: Xah Lee | last post by:
in March, i posted a essay “What is Expressiveness in a Computer Language”, archived at: http://xahlee.org/perl-python/what_is_expresiveness.html I was informed then that there is a academic...
53
by: jaso | last post by:
Can you give any comments on this code? I used one goto, is it bad? #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <assert.h> #define NOT_NULL 1
10
by: JoeC | last post by:
I have been programming for a while and I have seen this syntax before and I copied this from a book but the book didn't explain what is going on here. class engine{ protected: static engine*...
19
by: Eric | last post by:
What is this? ( char * ) &( ( struct aStruct * ) 0 ) It looks like it's taking the address of something that contains a pointer to null, and casting it to a pointer to char. (Actually,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
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:
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.