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
 
    