Skip to main content
Published: August 24 2006, 9:29:00 PMUpdated: November 28 2020, 2:28:45 PM

I keep getting "Object reference not set to an instance of an object" exceptions in my vb.net code.
Why is this happening?


Summary

You can avoid the "Object reference not set to an instance of an object" exception in vb.net by checking each object to make sure it is a valid object before attempting to access it.


Detailed Description

The "Object reference not set to an instance of an object" exception usually happens when you try to address an object that has not been set.
The SOAP API may not return certain elements or may not return certain container elements if there is no data to return.
In these cases, the corresponding SDK wrapper object will not be set.
Attempting to access such an object will result in an "Object reference not set to an instance of an object" exception.
Here is a concrete example in which we are using <IncludeContainingOrder>true</IncludeContainingOrder> in a GetItemTransactions call.
We expect the call to return a ContainingOrder object that has an OrderID.
However, the ContainingOrder "container" element is returned ONLY if the transaction is part of an Order.
The element is not returned if the transaction is not part of an Order.
Therefore we must make sure the ContainingOrder object is valid before accessing the OrderID as in the following code snippet.

    If Not (Transaction.ContainingOrder Is Nothing) Then
    {
         'you can now access Transaction.ContainingOrder.OrderID
    }
    Else
    {
         'you cannot access Transaction.ContainingOrder.OrderID
         'attempting to do so will cause "Object reference not set to an instance of an object"
    }
    End If

Even more fault tolerant would be the following snippet where we are doing a sanity check on the OrderID property also

    If Not (Transaction.ContainingOrder Is Nothing) Then
    {
         If Not (Transaction.ContainingOrder.OrderID Is Nothing) Then
         {
              'you can now access Transaction.ContainingOrder.OrderID
         }
         Else
         {
              ' we have a truly exceptional condition where the ContainingOrder container was returned with no OrderID
              ' this should NEVER happen
              ' we probably want to flag this and log it as an "exception" and report it as a bug along with the corresponding SDK call log
         }
    Else
    {
         'you cannot access Transaction.ContainingOrder.OrderID
         'attempting to do so will cause "Object reference not set to an instance of an object"
    }
    End If


Version Info

The instructions above apply to all versions of the .NET SDK.
Please note that the current recommendation on the oldest version of the SDK that you can use is Version 447.



Additional Resources

How well did this answer your question?
Answers others found helpful