Search code examples
c#idisposablenetworkcredentials

c# System.Net.NetworkCredential


System.Net.NetworkCredential does not have a Dispose method. What is the best way to handle properly disposing an object created using this class?

JamesNT


Solution

  • If an object does not implement IDisposable then the proper way to "dispose" of it when you are done using it, is to let it go out of scope.

    IDisposable is designed to allow the object to clean up any unmanaged resources it might be holding. If the object only contains managed resources, then there is no reason to dispose of it; everything will be cleaned up by the garbage collector.

    From MSDN:

    The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams.

    Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed.