Glossary / Culture-aware comparisons

Culture-aware comparisons

Culture-aware comparison interprets text according to linguistic rules for a culture, while ordinal comparison compares code units without linguistic interpretation. Choosing the correct comparison affects sorting, searching, security, and protocol correctness; user-facing text and identifiers often require different policies.

Comparison modes

Use StringComparison.Ordinal or OrdinalIgnoreCase for programmatic identifiers, keys, file extensions, protocol tokens, and security-sensitive comparisons where linguistic equivalence is unwanted. Use culture-aware modes such as CurrentCulture for user-facing sorting/searching, or InvariantCulture for culture-independent linguistic rules when that is specifically intended. Invariant culture is not equivalent to ordinal comparison.

bool tokenMatches = string.Equals(input, "admin", StringComparison.OrdinalIgnoreCase);

Culture-sensitive casing and sorting can produce different results across locales and runtime versions. The Turkish dotted/dotless I is a classic example. ToLower() without an explicit culture uses current culture and is unsafe as a general identifier normalization strategy. Prefer comparison overloads over allocating normalized strings.

Security and persistence

Use ordinal comparisons for authorization tokens, protocol keywords, and machine identifiers unless the protocol specifies otherwise. For database collation, sorting, and user search, align application expectations with database culture/collation. Persist normalized identifiers under a documented normalization and comparison policy.

Interview questions

  1. Ordinal vs culture-aware? Ordinal compares code units; culture-aware uses linguistic rules.
  2. What for protocol keywords? Ordinal (often ordinal-ignore-case if protocol says case-insensitive).
  3. Is invariant culture the same as ordinal? No; it is a culture-independent linguistic comparer.
  4. Why avoid ToLower() for comparisons? Culture dependence and allocations; use comparison overloads.
  5. How handle user sorting? Use culture-aware comparison matching user locale/product policy.

References