简体   繁体   中英

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".

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
}

A bit combersome C# 6.0 syntax ?. (instead of . in userDescription.Contains ) can be used

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

unfortunatelly (in this particular case) Boolean? can't be cast implicitly to Boolean and that's why == true should be added. In case of IndexOf the code looks quite OK:

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

You could override Contains() and IndexOf and define a custom output in case the string is null like this:

public static class Extensions
{
    public static bool Contains(this string value, string search)
    {
        if(value != null)
        {
            return value.Contains(search);

        }
        else
        {
            // IF ITS NULL DEFINE YOUR RETURN HERE
        }
        return false;
    }

    public static int IndexOf(this string value, string search)
    {
        if(value != null)
        {
            return value.IndexOf(search);
        }
        else
        {
            // IF ITS NULL DEFINE YOUR RETURN HERE
        }
        return -1;
    }
}

The usage stays the same except from the behaviour with null-values. Check my comments.

Before C# 6 using string.IsNullOrEmpty (or James Dev's answer) is necessary

var userDescription = (string)userDirectoryData.Properties["description"].Value;
if (!string.IsNullOrEmpty(userDescription) && userDescription.IndexOf("Contracted") > -1)
{
    continue;
}
else
{
    //Do Stuff here
}

With C# 6 you could reduce this to the null propagation operator ( ?. ):

if ((string)userDirectoryData.Properties["description"].Value?.IndexOf("Contracted") > -1)
{
    continue;
}
else
{
    //Do Stuff here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM