All objects consume system resources such as memory, file handles, and database connections. The Common Language Runtime (CLR) manages resources automatically, and you usually do not need to worry about releasing unneeded objects. However, understanding resource management works can help you design your applications to be more efficient.
The CLR uses a system called garbage collection to manage allocated resources. The system garbage collector releases an object's resources when that object can no longer be reached by any running code in your application. The following sections describe some of the changes to the way resources are managed in Visual Basic .NET.
Assigning Objects to Nothing
Nothing is a keyword used by Visual Basic .NET to indicate that an object variable does not contain a reference to an object. Previous versions of Microsoft Visual Basic encouraged you to assign unused objects to Nothing to disassociate the object variable from the object and release resources. You can still assign unused objects to Nothing, but because of the way Visual Basic .NET manages resources this process does not guarantee that objects will be released immediately. Generally speaking, you should only assign objects to Nothing for long-lived objects such as shared members or global variables.
Some objects support a method named Dispose whose purpose is to release system resources more expeditiously. Classes that support the Dispose method should implement the IDisposable interface. The Dispose method needs to be explicitly called when you want to release object resources. For example:
Another method supported by some classes, Finalize, runs automatically when an object is released and can be used to perform other cleanup tasks. The Finalize method is similar to the Class_Terminate() method used in previous versions of Microsoft Visual Basic. Unlike the Dispose method, the CLR automatically calls the Finalize method sometime after an object is no longer needed.
Nothing | Object Lifetime: How Objects Are Created and Destroyed | Initialization and Termination of Components | IDisposable.Dispose Method | IDisposable Interface