A nice Java Static String function I can now port into C# using Extension Methods

I have just been playing around making a small networking application using Java when i came across a small and dead simple function which I thought, "hey that is useful," and "oh that would now fit .NET Extension Methods."  So straight away lol and got my console up and had a play, and i know it may seem a bit trivial, but it is just a bit tidier than other methods you could use.  In all I just like the simple function of the .... function.  Working in a case sensitive language, it seems quite relevant to differentiate.

Anyway, enough blabbering, the function is called equalsIgnoreCase(String inValue) and to use in C# simply create a string extension method like so, with an implementation following:

    public static class StringExtensions
    {
        public static bool EqualsIgnoreCase(this string value, string compare)
        {
            return (compare.ToLower() == value.ToLower());
        }
    }

            Console.WriteLine("QuIt".EqualsIgnoreCase("quit"));

The output is True obviously :-)

Cheers,

Andrew

Published Friday, January 16, 2009 5:48 PM by REA_ANDREW
Filed under:

Comments

# re: A nice Java Static String function I can now port into C# using Extension Methods

Sunday, January 18, 2009 3:08 PM by Richard

The recommended approach for normalizing strings is to use upper-case, as several languages have multiple lower-case versions of a single upper-case letter.

Alternatively, why bother creating new copies of the strings at all? Just use the built-in String.Equals(String, String, StringComparison) method:

public static bool EqualsIgnoreCase(this string value, string compare)

{

   return string.Equals(value, compare, StringComparison.CurrentCultureIgnoreCase);

}

# re: A nice Java Static String function I can now port into C# using Extension Methods

Monday, January 19, 2009 3:55 AM by REA_ANDREW

Thanks for the comment Richard, I agree in the fact that I should have considered culture.  From your example then I will update the extension method:

   public static class StringExtensions

   {

       public static bool EqualsIgnoreCase(this string value, string compare)

       {

           return string.Equals(value, compare, StringComparison.CurrentCultureIgnoreCase);

       }

   }

Console.WriteLine("QuIt".EqualsIgnoreCase("quit"));

Thanks again for the Comment :-)

Andrew

Leave a Comment

(required) 
(required) 
(optional)
(required)