Search code examples
c#stringcontains

Using String.Contains on a Null value string


In my application I am getting the description filed from Active Directory and then assigning it to a string so I can later check that string for "Contracted" in order to ignore that users.
The problem is not all users have a value in the description field which results in a Null Reference Exception being thrown. The only way I can think of dealing with this is to add another check using String.IsNullOrEmpty and add a temp value, then later remove that temp value. This seems cumbersome and wrong.

What do I need to do to deal with null in the string during my check? I have tried the following two sets of code, both throw the error:

var userDescription = (string)userDirectoryData.Properties["description"].Value;

if (userDescription.Contains("Contracted"))
{
    continue;
}
else
{
    //Do Stuff here
}

And

var userDescription = (string)userDirectoryData.Properties["description"].Value;

if (userDescription.IndexOf("Contracted") > -1)
{
    continue;
}
else
{
    //Do Stuff here
}

EDIT: According to https://msdn.microsoft.com/en-us/library/k8b1470s.aspx I can't set to String.Empty as that will return a result of "0" causing a false positive the description only contains "Contracted".


Solution

  • Assign an empty string if the value is null using the c# nullable coalesce:

    var userDescription = (string)userDirectoryData.Properties["description"].Value ?? String.Empty;
    
    if (userDescription.Contains("Contracted"))
    {
        continue;
    }
    else
    {
        //Do Stuff here
    }