Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

dispose

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?

like image 604
Flagbug Avatar asked Dec 04 '22 08:12

Flagbug


2 Answers

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

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

}
like image 75
Stecya Avatar answered Jan 05 '23 00:01

Stecya


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).

like image 32
Bueller Avatar answered Jan 04 '23 23:01

Bueller