Click here to Skip to main content
15,891,763 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When we want to check not null in vb.net we use "IF Not X Is Nothing Then" but this is very vague to read and understand especially if code is complicated or large. Is there any condition with which we can check the same condition and easy to read or understand?

What I have tried:

reading vb.net articles. Followed some articles on stackoverflow and codeproject but no success.
Posted
Updated 10-Aug-17 19:40pm
Comments
Maciej Los 11-Aug-17 1:49am    

You could also write :
VB
IF x isnot Nothing then ...
but seen from the Content it's the same. But I can't see where this is "very vague" ... it is the way to do it ...
 
Share this answer
 
If that doesn't it too much the code performance, then place the condition (the 'ugly code') in a Shared method and give it an appealing name like, for instance, isAVeryGoodAndAliveReference.
 
Share this answer
 
Here is another variation using extension methods:
VB
Imports System.Runtime.CompilerServices

Module Module1

    Private FooBar As Foo = Nothing

    Sub Main()

        If (FooBar.IsNotNull) Then
            ' do something
        End If

    End Sub

End Module

Class Foo
    Public Property Bar As String
End Class

Module NullChecks

    <Extension>
    Function IsNull(Of T As Class)(ByVal obj As T) As Boolean
        Return obj Is Nothing
    End Function

    <Extension>
    Function IsNotNull(Of T As Class)(ByVal obj As T) As Boolean
        Return obj IsNot Nothing
    End Function

End Module
 
Share this answer
 
If x = Nothing then
'Do something (throw error,handle it) or ignore it
else
"Do what it is supposed to do if it is something
EndIf


Probably not the best way but a little more readable.
I use something like this for when a user didn't input data into a text box.
 
Share this answer
 
Comments
Maciej Los 11-Aug-17 1:47am    
Wrong approach. Check the documentation:
MSDN wrote:"When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing."
ledtech3 11-Aug-17 9:44am    
Thanks for the reference.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900