Share via


Sorting with Cultures

Sorting strings depends on the sort rules used to compare, and therefore order, pairs of strings. When your application performs a comparison operation, it can either explicitly specify the sort rule with one or more CompareOptions enumeration values or implicitly specify a sort rule with a CultureInfo object.

The .NET Framework supports word, string, and ordinal sort rules. A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. A string sort is similar to a word sort, except that there are no special cases and all nonalphanumeric symbols come before all alphanumeric Unicode characters. An ordinal sort compares strings based on the numeric value of each Char object in the string. For more information about word, string, and ordinal sort rules, see CompareOptions.

The .NET Framework represents strings with the String class, and each Unicode character in a string with a Char structure. Cultures are represented with the CultureInfo class, and culture-specific information that pertains to a comparison is represented by the CompareInfo class. The String and CompareInfo classes are the primary sources for comparison methods. Comparison operations use the culture associated with the current thread unless specified otherwise.

When and How to Compare with Cultures

Use the following guidelines to decide whether your application should perform a culture-sensitive comparison:

  • If your application requires a sort operation that depends on a particular culture, it should use a comparison method that specifies a CultureInfo object or CompareOptions enumeration parameter.

  • If the application requires a sort operation that is not specific to a particular culture, it should specify the invariant culture or use an ordinal sort. For example, an application uses an ordinal comparison to sort the names of files, mutexes, and named pipes. For more information about the invariant culture, see Using the InvariantCulture Property. For more information about an ordinal sort, see Normalization and Sorting.

  • If your application makes a security decision based on sorting strings, use an ordinal sort.

Important noteImportant Note:

Previous advice to use the invariant culture in a comparison operation that is used to make a security decision has been superseded. The application should use an ordinal comparison instead.

See Also

Concepts

Using the InvariantCulture Property

Normalization and Sorting