views:

67

answers:

4

What does the using statement do? Is it actually needed?

    using (MyWebservice x = new MyWebservice())
    {
    //random code
    }
+2  A: 

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.

Steven Pardo
A: 

No, it's not needed. We web service experts use it just to make sure you're paying attention.

John Saunders
You should explain precisely why it's not needed - i.e. not all programs need to work perfectly 100% of the time and if your business requirements specify a slow resource leak, omitting it is just the ticket to accomplish that.
Jesse C. Slicer
@Jesse: very good point. Another reason to omit it is if you want random errors like "database is already open", due to the fact that you didn't Dispose it last time around.
John Saunders
+1  A: 

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.

Oded
A: 

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);
}
}
DOK
-1: Please fix the SqlCommand object above, and please use XmlWriter.Create instead of XmlTextReader.
John Saunders
@John Saunders: I am not proposing these as "best practices" for their particular usage, just as examples of common applications for "using" statements. Could you elaborate on your problem with my SqlCommand? Like, which one?
DOK
@DOK: examples get copied and pasted. **Always** use IDisposable properly in examples, or those who copy the "just an example" will have bad code. Fix any of the SqlCommands that are not in a using block! That and everything else that implements IDisposable (with the possible exception of the DataTable).
John Saunders
@ John Saunders: OK, you're exhausting me. I was trying to illustrate the usage of "using", that's it. Just trying to be helpful. Other answers have discussed IDisposable; my answer is supplemental. People who copy and paste code from websites without understanding it do so at their own risk. I'll come back and kill my entire answer after you've had a chance to read this. That should improve your chances of getting another vote here.
DOK
@DOK: I think John's saying that your middle code-block which doesn't have the using statements on the SqlCommand should just be omitted so others don't attempt to use that - the last one is good as it uses using everywhere.
Jesse C. Slicer
@Jesse Slicer -- thanks for the clarification. I've made the change, hope it doesn't further infuriate John.
DOK