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.
 
Back
Top