The truth about string comparisons

Dave Fetterman – A dev on the BCL team wrote a very good MSDN article on strings.. Worth a read:

New Recommendations for Using Strings in Microsoft .NET 2.0

As you can probably tell by reading this bit, Dave did not cook to meet some column inches goal… we found some real-world issues in managed code our team was reviewing and felt it was important to clean up the platform AND guidance to developers.

Comments

  • Anonymous
    June 30, 2005
    On this recommendation:
    DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

    Why uppercase rather than lowercase? Is there any perticular reason?

  • Anonymous
    June 30, 2005
    "Why uppercase rather than lowercase? Is there any particular reason?"

    Michael Kaplan posted the answer to that question here:-
    http://blogs.msdn.com/bclteam/archive/2005/06/01/424012.aspx#comments

    His answer:
    There is a small range of characters that do not roundtrip, and going to lowercase will make these characters unavailable.
    For more info, see http://blogs.msdn.com/michkap/archive/2004/12/02/273619.aspx

  • Anonymous
    June 30, 2005
    This great article describes the situation as of beta 2 of Whidbey. Keep an eye open for an update when VS.NET 2005 is released - hopefully by then more methods in the String class will take the StringComparison enumeration as a parameter. IMO 'IndexOf', 'LastIndexOf', 'Contains' and 'Replace' also need it.

    Because the current 'Replace' is always case-sensitive, people have rolled their own to get case-insensitivity... and have got it wrong because they've failed to take into account cultural vs culturally-invariant vs ordinal comparisons.

    Whidbey can't come soon enough to sort out this mess.

  • Anonymous
    July 04, 2005
    Brad, is there any reason why Contains, IndexOf and such don't have an override with StringComparison?

  • Anonymous
    February 25, 2008
    I've had this come up in conversations in the past (and it's been on feedback for almost 3 years now

  • Anonymous
    February 25, 2008
    I've had this come up in conversations in the past (and it's been on feedback for almost 3 years