Comparing Strings Safely

Comparing Strings Safely

You often need to compare strings (or other data types), but sometimes a value could be null or DBNull if it’s coming from the database. The .NET Framework’s built-in comparison functions don’t handle nulls properly.

This function, and its overloaded version, compare the string value of an object and another string:

  private bool SafeCompare(object test, string testValue)
  {
   return SafeCompare(test, testValue, StringComparison.CurrentCultureIgnoreCase);
  }

  private bool SafeCompare(object test, string testValue, StringComparison compareSetting)
  {
   if (test != null)
   {
    if (!Convert.IsDBNull(test))
    {
     return String.Compare(test.ToString(), testValue, compareSetting) == 0;
    }
    else
     return false;
   }
   else
    return false;
  }

The function first tests the object against null, then against DBNull, and then against the string in question. Any null/DBNull value will cause the function to return false. The overloaded version also allows you to default the StringComparison value, which enables you to specify case-sensitive or case-insensitive comparisons.

Using this function as a model, you could easily add other overloads for non-string data types, such as doubles or integers. Here’s a version for comparing two integers “safely”:

  private bool SafeCompare(object test, integer testValue)
  {
   if (test != null)
   {
    if (!Convert.IsDBNull(test))
    {
     return Convert.ToInt32(test) == testValue;
    }
    else
     return false;
   }
   else
    return false;
  }

Because the parameter types are different, you can add this overloaded version to the other two shown above. This saves a lot of duplicated code and works around the inability to deal with nulls without throwing exceptions.

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.