views:

147

answers:

4

I believe these 2 lines are equivalent but after running into a strange issue I no longer believe this to be the case.

String mimeType = context.Request.ContentType;
(String.Compare("text/xml", mimeType, true) == 0))

is the same as :

context.Request.ContentType.ToLower().Equals("text/xml")

Are their implementations in the CLR any different?

+5  A: 

They are not completely equivalent; see here.

Here is the correct way to do a case insensitive comparison:

bool areSame = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);

This way will also be more efficient becasue it doesn't allocate a separate string for the lowercase copy.

SLaks
This will work for 99.999% of the cases, but might fail some times. See `The Turkish-I Problem` http://msdn.microsoft.com/en-us/library/ms973919.aspx
Gonzalo
@SLaks: I'm not sure what the point was, but `OrdinalIgnoreCase` does _not_ solve the Turkish-I problem.
Pavel Minaev
@Pavel: I didn't know that; thanks.
SLaks
You *should not* "solve" the Turkish I problem when comparing mime-types!
Craig Stuntz
A: 

the implementation of Compare(string, string, boolean) in .NET:

public static int Compare(string strA, string strB, bool ignoreCase)
{
    if (ignoreCase)
    {
        return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase);
    }
    return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
}

and Equals

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public bool Equals(string value)
{
    if ((value == null) && (this != null))
    {
        return false;
    }
    return EqualsHelper(this, value);
}

So, is NOT the same thing.

serhio
+5  A: 

They are not equivalent, and ToLower/ToUpper may have some localization issues. The way to compare two strings without case-sensitivity (considering one of the strings may be null, which is why I don't like the str1.Equals method) is the static String.Equals method:

bool areEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
mkedobbs
Preferred version because of safe `null` handling, but Gonzalo's comment to the other answer applies here as well, and should be taken into account.
Pavel Minaev
+1  A: 

In addition to the other answers (@SLaks, @Serhio), I also feel obligated to point out that .ToLower() generates another string. Compare does not as far as I know. Excessive string generation in an app can come back to bite you in terms of memory usage and performance if it is in frequently called code.

Jim Leonardo
I did point that out (in the last line)
SLaks
Hehe... see that now...
Jim Leonardo