Ben Blackmore
Ben Blackmore

Reputation: 45

Check for Null Value in VB.NET

I have a function that searches AD for an attribute (extensionAttribute3). It works fine if the attribute has a value, but if it's not set, it errors with 'Object reference not set to an instance of an object.' This always errors on the line:

CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString

I've tried using "If IsNothing" and "IsNot Nothing" to check for NULL values on both dirResult & CurrentPIN, but it still errors. How can I check for NULL values successfully?

Checking if dirResult is NULL:

Private Function GetUserProperties()
    Dim ADName As String = GetLogonName()
    Dim CurrentPIN As String = Nothing
    Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
    Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
    dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
    dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
    dirSearcher.SearchScope = SearchScope.Subtree
    Dim dirResult As SearchResult = dirSearcher.FindOne()
    If IsNothing(dirResult) Then
        Return "<not set>"
    Else
        CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
        Return CurrentPIN
    End If
End Function

Checking if CurrentPIN is NULL:

   Private Function GetUserProperties()
        Dim ADName As String = GetLogonName()
        Dim CurrentPIN As String = Nothing
        Dim dirEntry As DirectoryEntry = GetDirectoryEntry()
        Dim dirSearcher As DirectorySearcher = New DirectorySearcher(dirEntry)
        dirSearcher.Filter = ("(samAccountName=" & ADName & ")")
        dirSearcher.PropertiesToLoad.Add("extensionAttribute3")
        dirSearcher.SearchScope = SearchScope.Subtree
        Dim dirResult As SearchResult = dirSearcher.FindOne()
        CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
        If IsNothing(CurrentPIN) Then
            Return False
        Else
            Return CurrentPIN
        End If
    End Function

Upvotes: 1

Views: 11812

Answers (1)

Josh Part
Josh Part

Reputation: 2164

You should check for NULL in Properties("extensionAttribute3"):

If dirResult Is Nothing OrElse dirResult.GetDirectoryEntry.Properties("extensionAttribute3") Is Nothing Then
    Return "<not set>"
Else
    CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString
    Return CurrentPIN
End If

Explanation:

Is Nothing is IMO a cleaner way to check for NULLs, and AFAIK it also saves you a stack level.

If extensionAttribute3 doesn't have a value, you are having the exception because

CurrentPIN = dirResult.GetDirectoryEntry.Properties("extensionAttribute3").Value.ToString

is translated to

CurrentPIN = <NULL>.Value.ToString

Checking for NULL on dirResult is just to prevent a possible future exception.

Upvotes: 1

Related Questions