Dispose Objects (.NET)

When creating new objects in .NET, you must properly free the objects from memory through the disposal process and garbage collection. You use the Dispose method or the Using statement to signal when an object is ready for garbage collection. The Using statement in most cases is the preferred method, as it makes the proper calls to close and dispose of the object when it is no longer needed.

You need to dispose of an object under the following conditions:

VB.NET

' Dispose an object with the Using statement
Using <object> As <dataType> = <value>
    ' Do something here
End Using
 
' Manually dispose of an object with the Dispose method
<object>.Dispose()

C#

// Dispose an object with the using statement
using (<dataType> <object>  = <value>)
    // Do something here
}
 
// Manually dispose of an object with the Dispose method
<object>. Dispose ();