case-sensitive or case-insensitive comparison of characters

To compare two charactersfor equality with the flexibility of performing a case-sensitive or case-insensitive comparison we can create extension methods on the char type and use the Equals instance method on
the char structure to compare the two characters.

static class CharStrExtMethods
{
    public static bool IsCharEqual(this char firstChar, char secondChar)
    {
        return (IsCharEqual(firstChar, secondChar, false));
    }
    public static bool IsCharEqual(this char firstChar, char secondChar,
    bool caseSensitiveCompare)
    {
        if (caseSensitiveCompare)
        {
            return (firstChar.Equals(secondChar));
        }
        else
        {
            return (char.ToUpperInvariant(firstChar).Equals(
            char.ToUpperInvariant(secondChar)));
        }
    }
    public static bool IsCharEqual(this char firstChar, CultureInfo firstCharCulture,
    char secondChar, CultureInfo secondCharCulture)
    {
        return (IsCharEqual(firstChar, firstCharCulture,
        secondChar, secondCharCulture, false));
    }
    public static bool IsCharEqual(this char firstChar, CultureInfo firstCharCulture,char secondChar, CultureInfo secondCharCulture,bool caseSensitiveCompare)
    {
        if (caseSensitiveCompare)
        Controlling Case Sensitivity When Comparing Two Characters | 41
        {
        return (firstChar.Equals(secondChar));
        }
        else
        {
        return (char.ToUpper(firstChar, firstCharCulture).Equals(char.ToUpper(secondChar, secondCharCulture)));
        }
     }
}

The first overloaded IsCharEqual extension method takes only one parameter, which isthe character to be compared against the value contained in the current char instance. This extension method then calls the second IsCharEqual method with two parameters. The last parameter on this extension method call defaults to false so that when thismethod iscalled, you do not have to passin a value for the caseSensitiveCompare parameter—it will automatically default to false.

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.