-1

Possible Duplicate:
What is the C# Using block and why should I use it?

Whats the significance of using block? Why should i write my code inside using block?

eg:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString);
using (con)
{
    con.Open();            
    //
    // Some code
    //
    con.Close();
}

Is this the right way of using using statement?

Community
  • 1
  • 1
love Computer science
  • 1,824
  • 4
  • 20
  • 39

5 Answers5

1

using goes together with the IDisposable interface.

It guarantees that before exiting the scope the Dispose method would be called on the object in the using clause.

There is no other reason than that.

Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
1

using (x) {...} is nothing but syntactic sugar for

try
{
   ...
}
finally
{
  x.Dispose();
}
Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
0

The definition is: "Defines a scope, outside of which an object or objects will be disposed." More information can be found in the MSDN.

Rhapsody
  • 6,017
  • 2
  • 31
  • 49
0

When you are using an object that encapsulates any resource, you have to make sure that when you are done with the object, the object's Dispose method is called. This can be done more easily using the using statement in C#.

More info here: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx

Craig White
  • 13,492
  • 4
  • 23
  • 36
0

The using statement ensures that Dispose (of IDisposable) is called even if an exception occurs while you are calling methods on the object. In your example the SqlConnection will be closed and disposed at the end of the using block.

Your example is not the common way of defining a using block, because you could accidentally reuse con after the using block.

Try this:

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString))
{
    con.Open();            
    //
    // Some code
    //
}
Chaim Zonnenberg
  • 1,793
  • 13
  • 10