A comprehensive guide to C# string comparison covering all .NET comparison APIs: the == operator, string.Equals() with StringComparison, string.Compare(), and StringComparer for collections. Explains why the ToLower() pattern is an antipattern due to unnecessary allocations and the Turkish i problem. Covers Span-based allocation-free comparisons, case-insensitive dictionaries with StringComparer.OrdinalIgnoreCase, pattern matching in switch statements, and the new CompareOptions.NumericOrdering feature in .NET 10 for natural sort order. Includes practical examples for HTTP header parsing and configuration key lookup.
Table of contents
The Default: == Operatorstring.Equals() and StringComparisonThe ToLower() AntipatternThe Turkish i Problemstring.Compare(): Ordering and SortingStringComparer: For Collections and DictionariesSpan-Based Comparison (.NET 5+)Comparing with StartsWith and EndsWithString Equality in Switch Statements and Pattern MatchingPractical Example: Case-Insensitive Configuration ParserPractical Example: HTTP Header ComparisonComparison in Broader C# ContextsSummary: Rules of Thumb.NET 10: CompareOptions.NumericOrderingFAQSort: