What does the using statement do? Is it actually needed?
using (MyWebservice x = new MyWebservice())
{
//random code
}
What does the using statement do? Is it actually needed?
using (MyWebservice x = new MyWebservice())
{
//random code
}
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
No, it's not needed. We web service experts use it just to make sure you're paying attention.
It is syntactic sugar for the disposable pattern. When compiled it expands to the full patten in the generated IL code.
The object you initialize inside the ()
will get it Dispose
method called when it goes out of scope. This is why only classes that implement IDisposable
can use it.
See the MSDN article about it.
To answer your question "What does the using statement do?", here are some examples to illustrate more common usage of the using
statement to ensure the disposal referenced in the other answers:
Making sure that StringWriter and XmlTextWriter are disposed (closed) when we're finished using them:
using (StringWriter sw = new StringWriter(sb))
using (XmlTextWriter xw = new XmlTextWriter(sw))
{
WebPartManager1.ExportWebPart(partToExport, xw);
}
Making sure that both the database connection and the command object are disposed:
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection("ConnectionString"))
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "SELECT * FROM Customers";
connection.Open();
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
dt.Load(reader);
}
}