Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top