2nd use of using

  • Thread starter Thread starter soosan
  • Start date Start date
S

soosan

hi
what is the 2nd use of the using statment in c#..
the first one is for referencing namespaces.
thanx
 
For automatically calling Dispose on the objects defined within the using
statement when the execution path leaves the scope of the using statement,
as in

using (someObject)
{
// do stuff here
}
 
Dave said:
For automatically calling Dispose on the objects defined within the using
statement when the execution path leaves the scope of the using statement,

And, as a practical example, you can use that when working with databases to
ensure that a connection is closed whatever happens (this avoid having to
use the heavy try/catch/finally patern):

try
{
using (SqlConnection conn = new SqlConnection(source))
{
conn.Open();
//do somthing with the connection
}
}
catch {}

Here, even if an exception occurs in the using statement, the connection
will be disposed (thus closed) properly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top