473,659 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

beginner's question: usage of "using (...)"

Hello,
I have started larning C# and I have a question concerning "using
(...)" keyword.
For example:

using (SqlConnection connection = new SqlConnection(C onnectionString ))
{
connection.Open ();
....
connection.Clos e();
}

I can write it also this way:

SqlConnection connection;
try
{
connection = new SqlConnection(C onnectionString ));
connection.Open ();
....
connection.Clos e();
}
catch (...)
{
....
}
finally
{
....
}

But it won't dispose 'connection'.
Which solution is better? What are adventages and disadventages?
Thank you very much
/RAM/
Jun 21 '06 #1
2 1502
RAM,

When you have the using statement, the Dispose method on the IDisposable
implementation is called when the scope of the using statement is exited.

With the SqlConnection, calling Dispose is the same as calling Close, so
you don't have to explicitly call it. You can do this:

using (SqlConnection connection = new SqlConnection(C onnectionString ))
{
connection.Open ();

// Other stuff.
}

What this really compiles to is this:

SqlConnection connection = new SqlConnection(C onnectionString );

try
{
connection.Open ();

// Other stuff.
}
finally
{
if (connection != null)
{
// Call Dispose.
((IDisposable) connection).Dis pose();
}
}

So, if you have the need for exception handling, then you can use the
above construct and just insert the catch statements appropriately.

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

"R.A.M." <r_********@poc zta.onet.pl> wrote in message
news:16******** *************** *********@4ax.c om...
Hello,
I have started larning C# and I have a question concerning "using
(...)" keyword.
For example:

using (SqlConnection connection = new SqlConnection(C onnectionString ))
{
connection.Open ();
...
connection.Clos e();
}

I can write it also this way:

SqlConnection connection;
try
{
connection = new SqlConnection(C onnectionString ));
connection.Open ();
...
connection.Clos e();
}
catch (...)
{
...
}
finally
{
...
}

But it won't dispose 'connection'.
Which solution is better? What are adventages and disadventages?
Thank you very much
/RAM/

Jun 21 '06 #2
The main advantage of "using" is that it is easier to get it right, and
hence correctly dispose of objects. It saves you from having to do a
try / finally (which as your example shows, can be a mouthful), and
also deals with the situation where it initialises to null.

You can also have multiple same-level "using"s, and it will work
happily without having to worry about your "finally" barfing and so not
disposing all the objects - e.g.

using(Form f = new Form())
using(Button b = new Button()) {

// both f & b will be disposed as we exit this brace
}

That is obviously a lot tidier than the equivalent in try / finally
notation (remembering to dispose f if the b ctor throws, etc)

Finally, because of the above points, it saves you from excessive
indentation, which makes it easier to read (and thus support) the code.

"using" is your friend. Get to know it well ;-p

Marc

Jun 21 '06 #3

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

Similar topics

1
1832
by: Ka | last post by:
before some functions, such as @mkdir @mysql_query and what is the usage of that "@" signal??
2
8984
by: Lian | last post by:
Hi all, I am confused by the rule of comparing two unicode string using function "strcmp". For exmaple, using "strcmp" to compare two Chinese uincode string, depending on what rule can "PHP" decide one string is greater or less than the other string? Thank you for suggestions!
6
3670
by: Al Dykes | last post by:
I've just grabbed a PHP book and can deal with the syntax and now I need to decide to learn specific packages and features. Define "framework". What are the major framework flavors ? Under what conditions can I use two or more frameworks? Sorry for the beginners question.
2
16235
by: CoolPint | last post by:
Can anyone clearly explain the difference between constant reference to pointers and reference to constant pointers? What is const int * & ? Is it a constant reference to a pointer to an integer? Or Is it a reference to a pointer to a constant integer? What is being constant in this case? The pointer or the integer being pointed? How about int * const & ? Is this a reference to a constant pointer to an integer? Or
3
2283
by: Alessandro Brollo | last post by:
Far from a professional programmer, I'm simply a newbie Python user. Two basic questions: 1. I don't want to post banal questions about Python to main Python list. Does a "banal Python questions list" or a "Python beginners list" exist? 2. There is somewhere a very patient fellow willing to be my free "python tutor" by personal e-mailing outside the mail list? . The ideal candidate would be
14
2153
by: john.burton.email | last post by:
I've done some extensive searching and can't seem to find an answer to this - Is it correct to using "using" with templates, for example: using std::vector; Or do I need to specify the type too: using std::vector<int>; Both seem to "work" on the compiler I have and I can't find any documentation saying which is correct, or are both correct?
3
1378
by: ruud.bos | last post by:
Hi list, As a C++ newbie, I have a question about static member functions. Suppose I have the following class definition: class MyClass { public: static void MyFunc(); };
1
3185
by: | last post by:
I've got \\root\folder\Page2.aspx that I want to controll access to, by establishing a rule that says "previous URL must be '\\root\folder\Page1.aspx' (which did password validation). The code snippet below does 1) allow valid Page_Load if referring URL was 'Page1', and 2) disallows Page_Load if the *initial* access attempt was PRIOR to any valid load of 'Page2'... <code> // In Page_Load... // check the prior URL and make sure our...
22
3062
by: nospam_news | last post by:
I currently get asked about my usage of "auto". What is it for? The keyword is clearly superflous here. In contrast to the huge majority of C/C++ developers I write definitions very explicitly like that: int main(char argc, char *argv, char *env) { try { auto Exception mainException(1); mainException.setErrNo(42);
0
8851
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8539
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8630
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7360
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4176
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2759
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1982
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.