0

I have a class someone else wrote for which I don't have the source code. It has a property UM that is backed by _UM, a string. In some circumstances _UM is Nothing. I would expect that UM would be Nothing too, but when I inspect (using Quick Watch) the property it shows as a NullReferenceException. When I try testing for Nothing I get a NullReferenceException thrown in my main code. How can I catch this condition so I can handle it properly?

If Foo.UM Is Nothing Then
    DoSomething()
End If

...throws a NullReferenceException.

cjbarth
  • 4,189
  • 6
  • 43
  • 62

1 Answers1

1

The property might do more than just return the _UM field. Probably uses it somehow and does not take into account that it might be null. You could do something like this to handle it:

Dim obj = Nothing
Try
    obj = Foo.UM
Catch ex As NullReferenceException
End Try
If obj Is Nothing Then
    DoSomething()
End If
Magnus
  • 45,362
  • 8
  • 80
  • 118
  • I would agree that the property probably does something besides just return `_UM`, however, I don't particularly care. I just need to test and take action. Any thoughts on how to do that? – cjbarth Apr 17 '12 at 20:54
  • I was hoping to avoid that as it is quite a bit of overhead to process an exception...oh well. This class is quite lousy in other areas, I shouldn't be surprised. Thanks for your suggestion. – cjbarth Apr 17 '12 at 21:05
  • You can always decompile the external dll with Reflector for example and see what is actually going on in the property. – Magnus Apr 17 '12 at 21:17