How to: Make an Object Variable Not Refer to Any Instance (Visual Basic)

You can disassociate an object variable from any object instance by setting it to Nothing.

To disassociate an object variable from any object instance

  • Set the variable to Nothing in an assignment statement.

    ' Assume account is a defined class  
    Dim currentAccount As account  
    currentAccount = Nothing  
    

Robust Programming

If your code tries to access a member of an object variable that has been set to Nothing, a NullReferenceException occurs. If you set an object variable to Nothing frequently, or if it is possible the variable is not initialized, it is a good idea to enclose member accesses in a Try...Catch...Finally block.

.NET Framework Security

If you use an object variable for objects that contain confidential or sensitive data, you can set the variable to Nothing when you are not actively dealing with one of those objects. This reduces the chance of malicious code gaining access to the data.

See also