Saturday, March 24, 2012

Using String in .Net (2.0 and above)

A very interesting and eye-opening article about String handling within .Net can be found here.

It gives the following rules of thumb when it comes to Strings:


  • DO: Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • DO: Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.
  • DO: Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
  • DO: Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal orStringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).
  • DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.
  • DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
  • DON'T: Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.

Such a method can be used as follows:

String.Compare(strA, strB, StringComparsion.OrdinalIgnoreCase) 

No comments: