IsNothing alternative ?

T

tinman

Hi....

There appears to be another way of checking if an object IsNothing in
..NET.....was wondering if this approach is better than the classic VB6 way
of checking Is Nothing ?

Example
******

Public Function IsNothing(ByVal ExternalObject As Object) As Boolean
Try
Return (ExternalObject.Equals(New System.Object))
Catch ex As NullReferenceException
Return True
End Try
End Function

Private Sub Testing()
Dim objX as ClassX
Debug.WriteLine IsNothing(objX) 'Returns True
objX = New ClassX
Debug.WriteLine IsNothing(objX) 'Returns False
objX = Nothing
Debug.WriteLine IsNothing(objX) 'Returns True
End Sub
 
D

Daniel Pratt

Hi tinman,

Use "Is Nothing". The "Is Nothing" construct checks the value of the
reference directly, which is very fast. In your example, you are either
doing an unnecessary function call, or causing an exception, which is much
worse performance-wise.

Regards,
Daniel
 
D

David Browne

tinman said:
Hi....

There appears to be another way of checking if an object IsNothing in
.NET.....was wondering if this approach is better than the classic VB6 way
of checking Is Nothing ?

Example
******

Public Function IsNothing(ByVal ExternalObject As Object) As Boolean
Try
Return (ExternalObject.Equals(New System.Object))
Catch ex As NullReferenceException
Return True
End Try
End Function

No that's no good. Exceptions are relatively expensive to catch, and so you
don't want to use exceptions to trap common conditions like this.

Simple object reference equality will do the trick here.

if ExternalObject is nothing ...


David
 
H

Herfried K. Wagner [MVP]

* "tinman said:
There appears to be another way of checking if an object IsNothing in
.NET.....was wondering if this approach is better than the classic VB6 way
of checking Is Nothing ?

\\\
If ... Is Nothing Then
...
End If
///
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top