Share via


How to: Make an Object Variable Not Refer to Any Instance

You can disassociate an object variable from any object instance by setting it to Nothing (Visual Basic).

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.

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

Concepts

Object Variables in Visual Basic

Object Variable Assignment

Reference

Nothing (Visual Basic)

Try...Catch...Finally Statement (Visual Basic)

NullReferenceException

Troubleshooting Exceptions: System.NullReferenceException