.NET Tip: 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 built-in C# comparison functions don't handle nulls properly, so I wrote a couple of functions to take care of this for me.

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. I prefer to do a case-insensitive comparison in most cases, so that's the default value I send if that parameter is omitted.

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.

About the Author

Eric Smith is the owner of Northstar Computer Systems, a Web-hosting company based in Indianapolis, Indiana. He is also a MCT and MCSD who has been developing with .NET since 2001. In addition, he has written or contributed to 12 books covering .NET, ASP, and Visual Basic. Send him your questions and feedback via e-mail at questions@techniquescentral.com.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds