Revision: Case-Insensitive String Equality

I made revisions to my method for comparing strings while ignoring case.  This is in light of some good feedback I received.  Here is the updated method:

public static bool AreEqualIgnoreCase(string firstString, string secondString)
{
    // if references match (or both are null), quickly return
    if (firstString == secondString) return true;
    
    // if one is null, return false
    if (firstString == null || secondString == null ) return false;
    
    // with two different string instances, call Equals method 
    return firstString.Equals(secondString,
        StringComparison.InvariantCultureIgnoreCase);
}

With the above method, the following logic applies:

Strings.AreEqualIgnoreCase(null, null) == true;
Strings.AreEqualIgnoreCase(null, "string") == false;
Strings.AreEqualIgnoreCase("string", null) == false;
Strings.AreEqualIgnoreCase("string", "text") == false;
Strings.AreEqualIgnoreCase("string", "STRING") == true;

2 Comments

  • You can get exactly the same results with:

    string.Equals(firstString, secondString, StringComparison.InvariantCultureIgnoreCase)

    Apart from validating the comparisonType parameter, this method does exactly the same thing.

  • (sigh)

    Well, so much for reinventing the framework. Thanks Richard. It did not register with me that the StringComparison enum was also on the static Equals method of String.

Comments have been disabled for this content.