C # Testing for null

I use C # to write a simple program to read Active Directory and display the value stored in the AD field in a Windows programmatic form.

If the property does not exist, the program crashes, below is my code, how can I catch this and move on to the next field without doing a try / catch for each attribute?

DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");

//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
+3
source share
7 answers

Just checking usr.Properties["telephoneNumber"]will not work. You must check the actual value. The reason the error occurs is because you are calling ToString()on Value, which is null.

user.Properties PropertyValueCollection, , .

..

var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value;                  // Will return null and not error

, :

textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value 
                            ?? "Not found").ToString();
+8

usr.Properties["telephoneNumber"]; null:

PropertyValueCollection tel = usr.Properties["telephoneNumber"];

textBoxFirstName.Text = (tel != null && tel.Value != null)
                      ? tel.Value.ToString()
                      : "";
+3

- (??).

textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value 
                            ?? String.Empty).ToString();

, , null. null String.Empty, , , , ToString() null.

+2

- . , , .

textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null 
        ? usr.Properties["telephoneNumber"].Value.ToString()
        : "";
+1
if (usr.Properties["telephoneNumber"] != null)
    textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
0

:

  • usr.Properties [ "phoneNumber" ] null , Value. AD, . CLR, , NullReferenceException , , null.

  • , AD , Try-Catch, ( ).

0

SearchResult.Properties.Contains("property")

, ,

0

Source: https://habr.com/ru/post/1766032/


All Articles