Explicit clearing of variables

Code review rules

Object parameter not cleared, Object variable not cleared, Object variable clearing violation, Array [parameter] not deallocated and Array deallocation violation are the problems discussed on this page.

You can use Project Analyzer to require explicit clearing of object variables, deallocation of dynamic arrays and releasing of Win API resource handles. This group of review rules, part of the problem detection feature, helps you point out possible resource leaks, memory that is kept allocated after use and objects that stay live too long.

Object variables and dynamic arrays

Visual Basic automatically clears objects and deallocates arrays. In VB Classic, an object is destroyed when there are no more references to it. In .NET, an object is destroyed by a process called garbage collection. This process happens asynchronously. You can expect a .NET object to get destroyed after is not used any more, but you cannot determine the exact time when this happens.

Whether you use .NET or VB Classic, you have two approaches to variable clearing.

Here are the ways to explicitly clear your variables:

Set obj = Nothing ' VB 3-6 object variables
obj = Nothing     ' VB.NET object variables
Erase myArray     ' Dynamic arrays

Next follows an explanation of the various options on the Clearing tab in Problem Options.

Selection of the variables to monitor

Declare location and clearing rule

The clearing rules available are based on the scope of the variable in question. The declare locations Standard module and Class/form/structure are the more important ones. Procedure local variables and ByVal parameters can also be monitored for the sake of completeness.

Local object variables in .NET. Due to the nature of garbage collection (GC) in .NET, you may want to avoid explicit clearing of local object variables while requiring clearing for non-local ones. A local variable is subject to garbage collection after the line where it is mentioned the last time. After this line it's dead to .NET and ready to be garbage collected. If you explicitly clear the variable at the end of a long procedure you may actually be keeping it alive for a longer time than expected. By letting .NET handle the clearing of local objects you may end up with more efficient GC.


The following variables are not monitored: Static arrays. Object fields in user-defined Types (VB Classic). Variants in VB Classic and Objects in .NET, as they may contain non-object values. String variables, even though it makes sense to clear string variables to deallocate memory. Properties are not monitored either.

Comment directive

The comment directive parameter for this set of rules is CLEAR. They are also covered by the parameter STYLE.

See also

Problem detection
Code review rules

Project Analyzer Help