Friday, July 01, 2005

Recommendations for using Strings in 2.0

I read an article in MSDN by Dave New Recommendations for Using Strings in Microsoft .NET 2.0. Extract below:

Code owners previously using the InvariantCulture for string comparison, casing, and sorting should strongly consider using a new set of String overloads in Microsoft .NET 2.0. Specifically, data that is designed to be culture-agnostic and linguistically irrelevant should begin specifying overloads using either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase members of the new StringComparison enumeration. These enforce a byte-by-byte comparison similar to strcmp that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.

Recommendations for String Use
When developing with the 2.0 version of the .NET Framework, keeping a few very simple recommendations in mind will suffice to solve confusion about using strings.

Do's:

  1. Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  2. Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.
  3. Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
  4. Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).
  5. Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

Dont's:

  1. Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
  2. Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.
A read of the article would surely give an insight towards best practices for string comparison.... excellent article...

No comments: