Do I need to dispose of returned objects that I do not 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 need to get rid of the WebResponse object returned by WebRequest ?

+4
source share
3 answers

You must. Wrap it in a using statement and it will be automatically deleted when you exit the scope

 using (var response = request.GetResponse()) { } 
+10
source

As far as I have to dispose, I would say no. When the CLR detects that there are no object references, the object will be assigned to garbage collection. The problem you will encounter is that there is no guarantee that the object and its attributes will be cleaned in the correct order. Simple objects / classes, whether part of the .NET Framework or custom objects / classes, rarely implement the iDisposable interface. If an object / class implements iDisposable, you must definitely call the dispose method to ensure that the cleanup is processed correctly, as the designer had some indications of the need for cleanup in a specific order. As Stecya stated, the wrapper in the block used is a great way to see that this is done automatically. You can also use the try / finally block to achieve the same goal (disposing of an object in a finally block).

+4
source

Yes you should. And you are right that this is not entirely obvious, usually you should use only Dispose objects created by you (using new ) and leave those that you get / occupy only from another component.

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

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

+3
source

All Articles