Flagbug
Flagbug

Reputation: 2103

Do I have to dispose of returned objects that I don't use?

I have the following code:

WebRequest request = WebRequest.Create("ftp://myServer/myDirectory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("userName", "password");

request.GetResponse();

Do I have to dispose of the WebResponse object that is returned by the WebRequest?

Upvotes: 4

Views: 266

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273274

Yes you should. And you're right that that is not totally obvious, normally you should only Dispose objects you created (with new) and leave those you get/borrow from another component alone.

The key is in the name and description of WebRequest.Create(), it is a factory method that creates something on your behalf and the caller (you) is responsible for the return value.

And of course the preferred syntax is a using() {} block.

Upvotes: 3

Bueller
Bueller

Reputation: 2344

As far as HAVE to dispose, I would say no. When the CLR detects there are no references to the object, the object will be scheduled for garbage collection. The problem you may run into is that there are no guarantees that the object and its attributes will be cleaned up in the correct order. Simple objects/classes, whether part of the .NET Framework or custom objects/classes rarely implement iDisposable interface. If an object/class implements iDisposable, you should definitely call the dispose methode to ensure proper handling of the clean up as the designer had some indication that it was necessary to clean up in a particular way. As stated by Stecya, wrapping in a using block is a great way to see this is done automatically. You could also use a try/finally block to achieve the same thing (disposing of the object in the finally block).

Upvotes: 4

Stecya
Stecya

Reputation: 23266

You should. Wrap it in using statement and it will be automatically disposed when going out of scope

using (var response = request.GetResponse())
{

}

Upvotes: 10

Related Questions