Search code examples
c#.netdispose

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?


Solution

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

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