C# StringComparison
last modified November 15, 2026
This article shows how to compare strings in C# with the
StringComparison enumeration. We cover ordinal and
culture-sensitive comparison, sorting, culture-specific rules, the Turkish
I problem, ignorable characters, compare options, natural sorting, and
case-insensitive collections.
Strings can be compared in two fundamentally different ways. An
ordinal comparison compares the numeric values of the UTF-16 code
units, one by one. It is fast and predictable. A culture-sensitive
(linguistic) comparison follows the rules of a human language: it knows
that a and A belong together in a dictionary,
that accented letters sort next to their base letters, and that some
characters are ignored entirely. On Linux and macOS, and on Windows since
.NET 5, .NET uses the ICU library for linguistic comparisons.
The StringComparison enumeration selects the kind of
comparison. It has six members: CurrentCulture,
InvariantCulture, and Ordinal, each in a
case-sensitive and a case-insensitive variant. Methods such as
Equals, Compare, StartsWith,
IndexOf, and Replace accept it as a parameter.
The general rule: use Ordinal or
OrdinalIgnoreCase for identifiers, keys, file names, protocol
elements, and other machine-oriented text; use a culture comparison for
text shown to users, such as sorted lists of names.
The six comparison kinds
The first example compares two strings that differ only in case with all six members of the enumeration.
string a = "falcon";
string b = "FALCON";
foreach (StringComparison sc in Enum.GetValues<StringComparison>())
{
Console.WriteLine($"{sc,-27} {string.Equals(a, b, sc)}");
}
We iterate over the values of the enumeration.
foreach (StringComparison sc in Enum.GetValues<StringComparison>())
{
Console.WriteLine($"{sc,-27} {string.Equals(a, b, sc)}");
}
The Enum.GetValues<T> method returns the members. The
case-insensitive variants consider the strings equal. The plain
a == b and a.Equals(b) calls use ordinal
comparison.
$ dotnet run CurrentCulture False CurrentCultureIgnoreCase True InvariantCulture False InvariantCultureIgnoreCase True Ordinal False OrdinalIgnoreCase True
Sorting
Ordinal and linguistic comparisons often give a different order. The
StringComparer class provides comparers that can be passed to
sorting methods.
using System.Globalization;
string[] words = ["zebra", "Apple", "apple", "Zebra", "éclair", "eagle", "banana"];
Console.WriteLine(string.Join(" ", words.Order(StringComparer.Ordinal)));
Console.WriteLine(string.Join(" ", words.Order(StringComparer.InvariantCulture)));
Console.WriteLine(string.Join(" ", words.Order(StringComparer.OrdinalIgnoreCase)));
Console.WriteLine(string.Compare("apple", "Apple", StringComparison.Ordinal));
Console.WriteLine(string.Compare("apple", "Apple", StringComparison.InvariantCulture));
We sort a few words with three comparers.
Console.WriteLine(string.Join(" ", words.Order(StringComparer.Ordinal)));
In ordinal order, all uppercase ASCII letters (65–90) come before
lowercase ones (97–122), and the letter é (233)
comes after all of them. This is rarely what users expect.
Console.WriteLine(string.Join(" ", words.Order(StringComparer.InvariantCulture)));
The invariant culture puts words in dictionary order. Case matters only as
a tie-breaker, with lowercase first, and éclair sorts
among the words starting with e.
Console.WriteLine(string.Compare("apple", "Apple", StringComparison.Ordinal));
Console.WriteLine(string.Compare("apple", "Apple", StringComparison.InvariantCulture));
The ordinal comparison returns the difference of the first differing code units, 97 − 65 = 32. Only the sign of the result is meaningful. The two kinds of comparison disagree even on the sign here.
$ dotnet run Apple Zebra apple banana eagle zebra éclair apple Apple banana eagle éclair zebra Zebra Apple apple banana eagle zebra Zebra éclair 32 -1
Culture-specific rules
Each culture has its own collation rules. In Slovak and Czech, the
digraph ch is a separate letter that comes after
h.
using System.Globalization;
string[] words = ["hora", "chata", "cesta", "ihla", "hrad"];
var en = StringComparer.Create(new CultureInfo("en-US"), ignoreCase: false);
var sk = StringComparer.Create(new CultureInfo("sk-SK"), ignoreCase: false);
Console.WriteLine(string.Join(" ", words.Order(en)));
Console.WriteLine(string.Join(" ", words.Order(sk)));
We sort Slovak words with the English and the Slovak culture.
var sk = StringComparer.Create(new CultureInfo("sk-SK"), ignoreCase: false);
The StringComparer.Create method creates a comparer for a
specific culture. The Slovak comparer places chata after
hrad, while the English comparer places it after
cesta. This is the reason why user-facing sorting should use
the culture of the user.
$ dotnet run cesta chata hora hrad ihla cesta hora hrad chata ihla
The Turkish I problem
The current culture comparisons depend on the regional settings of the machine. This can break code that compares identifiers.
using System.Globalization;
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
string cmd = "file";
string input = "FILE";
Console.WriteLine(cmd.ToUpper());
Console.WriteLine(cmd.ToUpperInvariant());
Console.WriteLine(string.Equals(cmd, input, StringComparison.CurrentCultureIgnoreCase));
Console.WriteLine(string.Equals(cmd, input, StringComparison.OrdinalIgnoreCase));
We set the current culture to Turkish and compare a command name.
Console.WriteLine(cmd.ToUpper());
Turkish has a dotted and a dotless i. The uppercase form of
i is İ (capital I with dot above), so
file becomes FİLE, not
FILE.
Console.WriteLine(string.Equals(cmd, input, StringComparison.CurrentCultureIgnoreCase)); Console.WriteLine(string.Equals(cmd, input, StringComparison.OrdinalIgnoreCase));
A program that accepts the FILE command works on an English
system and fails on a Turkish one. The OrdinalIgnoreCase
comparison does not depend on the culture.
$ dotnet run FİLE FILE False True
Ignorable characters
Linguistic comparison ignores some characters completely, for instance the soft hyphen (U+00AD) or the zero-width joiner. Ordinal comparison treats them as any other character. Methods that use different defaults then give inconsistent results.
string word = "co\u00ADoperate";
Console.WriteLine(word.Length);
Console.WriteLine(word.StartsWith("coop"));
Console.WriteLine(word.StartsWith("coop", StringComparison.Ordinal));
Console.WriteLine(word.Contains("coop"));
Console.WriteLine(word.Contains("coop", StringComparison.CurrentCulture));
Console.WriteLine(string.Equals(word, "cooperate", StringComparison.InvariantCulture));
Console.WriteLine(string.Compare(word, "cooperate", StringComparison.InvariantCulture));
Console.WriteLine("falcon".IndexOf("\u00AD"));
Console.WriteLine("falcon".IndexOf("\u00AD", StringComparison.Ordinal));
The word contains an invisible soft hyphen, a hint where the word may be broken at the end of a line.
Console.WriteLine(word.StartsWith("coop"));
Console.WriteLine(word.StartsWith("coop", StringComparison.Ordinal));
The StartsWith(string) overload without a comparison argument
uses the current culture and skips the soft hyphen. With
Ordinal, the soft hyphen is a character like any other.
Console.WriteLine(word.Contains("coop"));
Console.WriteLine(word.Contains("coop", StringComparison.CurrentCulture));
The Contains(string) overload, in contrast, is ordinal by
default. The defaults are a historical inconsistency:
StartsWith, EndsWith, IndexOf(string),
Compare, and CompareTo are culture-sensitive,
whereas Equals, ==, Contains,
Replace, and IndexOf(char) are ordinal. Passing
the comparison explicitly makes the intent clear; the CA1307 and CA1309
code analysis rules suggest it.
Console.WriteLine("falcon".IndexOf("\u00AD"));
A culture-sensitive search for an ignorable character finds an empty match at position 0, as if we searched for an empty string. The ordinal search correctly reports that the character is not there.
$ dotnet run 10 True False False True True 0 0 -1
Compare options and natural sorting
The CompareOptions enumeration gives finer control over
linguistic comparison than StringComparison. It is used with
the CompareInfo class and with
StringComparer.Create.
using System.Globalization;
CompareInfo ci = CultureInfo.InvariantCulture.CompareInfo;
Console.WriteLine(ci.Compare("cafe", "café", CompareOptions.None));
Console.WriteLine(ci.Compare("cafe", "café", CompareOptions.IgnoreNonSpace));
Console.WriteLine(ci.IndexOf("Crème brûlée", "brulee",
CompareOptions.IgnoreNonSpace));
string[] files = ["file10.txt", "file2.txt", "file1.txt", "File3.txt"];
var natural = StringComparer.Create(CultureInfo.InvariantCulture,
CompareOptions.NumericOrdering | CompareOptions.IgnoreCase);
Console.WriteLine(string.Join(" ", files.Order(StringComparer.OrdinalIgnoreCase)));
Console.WriteLine(string.Join(" ", files.Order(natural)));
We ignore accents and sort file names in natural order.
Console.WriteLine(ci.Compare("cafe", "café", CompareOptions.IgnoreNonSpace));
The IgnoreNonSpace option ignores diacritics, so
cafe and café are equal. Without it,
cafe sorts before café.
Console.WriteLine(ci.IndexOf("Crème brûlée", "brulee",
CompareOptions.IgnoreNonSpace));
The option also works for searching: we find brulee written
without accents.
var natural = StringComparer.Create(CultureInfo.InvariantCulture,
CompareOptions.NumericOrdering | CompareOptions.IgnoreCase);
The NumericOrdering option, added in .NET 10, compares
sequences of digits by their numeric value. A plain comparison puts
file10.txt before file2.txt; the natural order
puts it last, as file managers do.
$ dotnet run -1 0 6 file1.txt file10.txt file2.txt File3.txt file1.txt file2.txt File3.txt file10.txt
Case-insensitive collections
Dictionaries and sets accept a StringComparer in the
constructor. The comparer determines both equality and hash codes of the
keys.
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["Content-Type"] = "text/html",
["Content-Length"] = "1024"
};
Console.WriteLine(headers["content-type"]);
Console.WriteLine(headers.ContainsKey("CONTENT-LENGTH"));
var tags = new HashSet<string>(["CSharp", "dotnet", "csharp", "DotNet", "linq"],
StringComparer.OrdinalIgnoreCase);
Console.WriteLine(string.Join(" ", tags));
HTTP header names are case-insensitive, so we store them in a dictionary with an ordinal case-insensitive comparer.
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
The lookups succeed regardless of the case of the key.
var tags = new HashSet<string>(["CSharp", "dotnet", "csharp", "DotNet", "linq"],
StringComparer.OrdinalIgnoreCase);
The set removes duplicates that differ only in case. It keeps the first occurrence of each tag.
$ dotnet run text/html True CSharp dotnet linq
Searching and replacing
Many string methods have overloads with a StringComparison
parameter.
string text = "An old falcon. The FALCON flies. A falcon sleeps.";
Console.WriteLine(text.Replace("falcon", "hawk"));
Console.WriteLine(text.Replace("falcon", "hawk", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.Contains("FALCON flies"));
Console.WriteLine(text.Contains("falcon flies", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.EndsWith("SLEEPS.", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.Split("falcon", StringSplitOptions.TrimEntries).Length);
We replace and search text without regard to case.
Console.WriteLine(text.Replace("falcon", "hawk"));
Console.WriteLine(text.Replace("falcon", "hawk", StringComparison.OrdinalIgnoreCase));
The default Replace is ordinal and case-sensitive, so it skips
FALCON. The overload with OrdinalIgnoreCase
replaces all three occurrences.
Console.WriteLine(text.Split("falcon", StringSplitOptions.TrimEntries).Length);
Not every method has such an overload. Split always
compares ordinally; it splits on the two lowercase occurrences only and
returns three parts. For case-insensitive splitting we would use
Regex.Split with RegexOptions.IgnoreCase.
$ dotnet run An old hawk. The FALCON flies. A hawk sleeps. An old hawk. The hawk flies. A hawk sleeps. True True True 3
Source
Best practices for comparing strings in .NET
In this article we have compared strings in C# with
StringComparison. See also the
IComparer,
string,
IEquatable, and
grapheme tutorials.
Author
List all C# tutorials.