BrandGhost
C# String Comparison: Equals, OrdinalIgnoreCase, StringComparer, and Culture Pitfalls
All articles

C# String Comparison: Equals, OrdinalIgnoreCase, StringComparer, and Culture Pitfalls

Master C# string comparison with Equals, OrdinalIgnoreCase, StringComparer, and culture-sensitive APIs. Avoid the ToLower() antipattern and Turkish i problem.

C# string comparison starts with two decisions: are you checking equality or sorting, and does the text need linguistic rules? For culture-independent identifiers, use ordinal comparison. Choose Ordinal when case matters and OrdinalIgnoreCase when your identifier contract explicitly ignores case.

Don't make every string case-insensitive. A command name, a display name, and a case-sensitive token can have different requirements even when all three are stored as string.

Reader task Starting point
Case-sensitive identifier equality string.Equals(a, b, StringComparison.Ordinal)
Case-insensitive identifier equality string.Equals(a, b, StringComparison.OrdinalIgnoreCase)
Linguistic equality using the current culture string.Equals(a, b, StringComparison.CurrentCulture) or its ignore-case variant
Case-insensitive dictionary keys StringComparer.OrdinalIgnoreCase, if the key contract permits it
Sorting text for a particular audience A StringComparer for the appropriate culture and case rules
Sorting labels containing digit sequences A culture comparer with CompareOptions.NumericOrdering, on .NET 10+

As of November 18, 2026, .NET 11 is the latest stable runtime generation and C# 15 has been released. The examples use supported .NET 10 LTS and its default C# 14 language version so the guide remains useful without requiring an upgrade to .NET 11.

Each top-level C# block is a separate console example. Use a .NET 10 console project with its default implicit usings and nullable reference types enabled. The ConfigParser class is a separate class-file example.


Equality: == and string.Equals

For operands statically typed as string, the == operator compares string contents using ordinal, case-sensitive equality. It does not merely check whether the two variables reference the same object.

string a = "Hello";
string b = new string(new[] { 'H', 'e', 'l', 'l', 'o' });
string c = "hello";

Console.WriteLine(a == b);
Console.WriteLine(a == c);

Expected output: True, then False.

== is reasonable when you intend ordinal, case-sensitive string equality. For other rules, use an explicit StringComparison:

string? input = "ADMIN";

Console.WriteLine(string.Equals(input, "admin", StringComparison.Ordinal));
Console.WriteLine(string.Equals(input, "admin", StringComparison.OrdinalIgnoreCase));
Console.WriteLine(string.Equals(null, null, StringComparison.Ordinal));
Console.WriteLine(string.Equals(null, "", StringComparison.Ordinal));

Expected output: False, True, True, False.

The static overload handles null operands. Calling an instance method such as input.Equals(...) requires a non-null receiver.

The defaults are not all the same

Operation Default string-comparison behavior
a == b, with both operands typed as string Ordinal, case-sensitive equality
string.Equals(a, b) Ordinal, case-sensitive equality
a.Equals(b), with a string argument Ordinal, case-sensitive equality
string.Compare(a, b) Current-culture, case-sensitive ordering
a.CompareTo(b) Current-culture, case-sensitive ordering
a.StartsWith("text") or a.EndsWith("text") Current-culture, case-sensitive matching

That fourth row matters. string.Compare(a, b) does not default to ordinal comparison.

Prefer overloads that make comparison intent explicit when choosing between linguistic and ordinal behavior. There is no need to replace a clear string == expression merely to make it longer. Also check the exact overload: character-based search APIs don't necessarily have the same defaults as string-based ones.


Choosing a StringComparison

The six values combine culture and case rules:

Value Meaning Suitable use
Ordinal Non-linguistic, case-sensitive comparison Case-sensitive symbolic keys or tokens
OrdinalIgnoreCase Non-linguistic comparison that ignores case Keys or commands defined to be case-insensitive
CurrentCulture Case-sensitive linguistic comparison using the current culture Language-sensitive text matching
CurrentCultureIgnoreCase Current-culture linguistic comparison that ignores case Language-sensitive matching where case should not matter
InvariantCulture Case-sensitive linguistic comparison using the invariant culture Explicitly invariant linguistic requirements
InvariantCultureIgnoreCase Invariant linguistic comparison that ignores case Those requirements when case should not matter

InvariantCulture is still a linguistic comparison. It is not another name for ordinal comparison, and storing text in a file or database doesn't automatically make it the right choice.

Formatting a number or date with invariant culture for persistence is a separate decision from comparing identifiers. Microsoft's string-comparison guidance makes that distinction.

Ordinal comparison works on UTF-16 code units, not bytes or human-perceived characters. It doesn't automatically make canonically equivalent Unicode spellings equal. For example, an accented letter can be represented as one code point or as a base letter plus a combining mark.

If your data contract requires equivalent Unicode forms to share an identity, define a Unicode normalization policy as well as comparison rules. Ignoring case and Unicode normalization solve different problems.


Avoid Lowercasing Just to Compare

Converting text to lowercase before checking equality mixes casing work with the comparison rule:

string input = "ADMIN";

bool viaCurrentCulture = input.ToLower() == "admin";
bool viaInvariantCasing = input.ToLowerInvariant() == "admin";
bool explicitComparison = string.Equals(
    input,
    "admin",
    StringComparison.OrdinalIgnoreCase);

Console.WriteLine(explicitComparison);

Expected output: True.

For an identifier whose contract ignores case, the last expression states the requirement directly. It also avoids creating an intermediate lowercased string.

Each lowercasing expression makes one casing call. Whether that call allocates depends on the input and implementation. Don't assume a fixed allocation count without measuring the actual code and workload.

There are legitimate reasons to canonicalize text, including a protocol or storage format that requires a particular representation. Apply that specified policy when needed. For a one-off equality check, choose the comparison rule instead of manufacturing a transformed copy.


The Turkish i Problem

Case conversion depends on culture. In Turkish, lowercase i maps to uppercase \u0130 -- a capital I with a dot -- rather than the ASCII I.

using System.Globalization;

var turkish = CultureInfo.GetCultureInfo("tr-TR");
string upper = "file".ToUpper(turkish);

Console.WriteLine(upper == "F\u0130LE");
Console.WriteLine(upper == "FILE");
Console.WriteLine(string.Equals(
    "file",
    "FILE",
    StringComparison.OrdinalIgnoreCase));

Expected output: True, False, True. This culture example requires globalization support; it isn't intended for globalization-invariant mode.

The example selects Turkish explicitly, so it doesn't depend on your machine's default locale. Turkish casing isn't broken. It is the wrong rule when the application intends culture-independent matching of an ASCII command or identifier.

Use ordinal comparison for that symbolic contract. Whether it should ignore case is a second decision.


string.Compare: Ordering, Not a Boolean Answer

Use equality APIs to ask whether values match. Use comparison APIs when you need an ordering:

int result = string.Compare(
    "apple",
    "banana",
    StringComparison.Ordinal);

Console.WriteLine(result < 0);

Expected output: True.

A negative result means the first value sorts before the second; zero means they compare equal under the selected rules; a positive result means the first sorts after the second. Don't depend on the result being exactly -1 or 1.

For a collection, pass a comparer that matches the data:

using System.Globalization;

var names = new List<string> { "Zebra", "apple", "Mango", "banana" };
var displayComparer = StringComparer.Create(
    CultureInfo.GetCultureInfo("en-US"),
    ignoreCase: true);

names.Sort(displayComparer);
Console.WriteLine(string.Join(", ", names));

This chooses English linguistic sorting explicitly. In a UI that follows the current culture, StringComparer.CurrentCultureIgnoreCase is another option.

The default List<string>.Sort() uses the string type's current-culture ordering. That isn't inherently wrong; it's a choice you should recognize. Exact linguistic ordering can depend on the selected culture and globalization data, so don't assume one universal alphabetical order.

Ignoring case also doesn't turn a comparer into a numeric or semantic-version sorter.


StringComparer for Dictionaries and Sets

StringComparer implements both IComparer<string> and IEqualityComparer<string>. It lets sorting and keyed collections receive an appropriate strategy.

For a case-insensitive command dictionary:

var commands = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["start"] = "Starting",
    ["stop"] = "Stopping"
};

Console.WriteLine(commands["START"]);
Console.WriteLine(commands.ContainsKey("Stop"));

Expected output: Starting, then True.

Use StringComparer.Ordinal instead if start and START must be distinct keys. Once you've chosen the dictionary's comparer, you don't need to lowercase every incoming key.

A sorted set uses comparison results for ordering and uniqueness:

var commands = new SortedSet<string>(StringComparer.OrdinalIgnoreCase)
{
    "start",
    "Stop",
    "STATUS"
};

Console.WriteLine(commands.Contains("START"));
Console.WriteLine(commands.Add("START"));
Console.WriteLine(commands.Count);

Expected output: True, False, 3. The second spelling doesn't add a distinct item under this comparer.

C# 15 adds collection expression arguments, including a way to provide a comparer in a collection expression. The examples keep constructor syntax for the .NET 10/C# 14 baseline; the comparison decision is the same.


Span-Based Comparison Without a Substring

When you're comparing a slice of existing text, ReadOnlySpan<char> can avoid allocating a separate substring:

string line = "Content-Type: application/json";

bool isContentType = line.AsSpan(0, 12).Equals(
    "Content-Type".AsSpan(),
    StringComparison.OrdinalIgnoreCase);

Console.WriteLine(isContentType);

Expected output: True.

This uses the character-span equality overload with explicit rules. The slice and comparison don't require an intermediate substring object. This is not a claim that the entire program, including output, allocates nothing.

Know the input boundaries before slicing. AsSpan(0, 12) is valid for this known line; a general parser must check lengths and delimiters.


StartsWith, EndsWith, URLs, and File Paths

The string overloads of StartsWith and EndsWith accept StringComparison. Use an overload that expresses the intended rule:

string text = "HTTPS://www.devleader.ca/blog";

Console.WriteLine(text.StartsWith(
    "https://",
    StringComparison.OrdinalIgnoreCase));
Console.WriteLine(text.EndsWith(
    "/blog",
    StringComparison.Ordinal));

bool spanPrefix = text.AsSpan().StartsWith(
    "https://".AsSpan(),
    StringComparison.OrdinalIgnoreCase);
Console.WriteLine(spanPrefix);

Expected output: True, True, True.

That is a prefix/suffix demonstration, not URL validation or an authorization check. A query or fragment can also change what a raw URL string ends with. Use Uri.TryCreate and inspect the relevant components when interpreting URLs.

URI schemes and hosts are case-insensitive. That doesn't make every path, query value, or entire URL case-insensitive; those components follow their own scheme/application rules.

Likewise, don't choose filename equality solely from a Windows/Linux label. Follow the actual filesystem and directory configuration. Windows supports per-directory case sensitivity, for example. An ordinal string comparison also doesn't resolve aliases, symbolic links, or whether two paths identify the same file.


Case-Insensitive Switch Expressions

String literal patterns use ordinal, case-sensitive matching. For a small case-insensitive command dispatcher, guards make the chosen rule explicit:

string? command = "START";

string result = command switch
{
    _ when string.Equals(command, "start", StringComparison.OrdinalIgnoreCase)
        => "Starting...",
    _ when string.Equals(command, "stop", StringComparison.OrdinalIgnoreCase)
        => "Stopping...",
    _ => "Unknown command"
};

Console.WriteLine(result);

Expected output: Starting.... A null command reaches the fallback because the guarded static equality calls handle null.

Converting once with ToUpperInvariant() before switching can be a deliberate normalization strategy, but it does extra casing work and needs null handling. The guarded version keeps this example focused on comparison. For a larger dispatch table, a dictionary with the appropriate comparer may be simpler.


Practical Example: Read-Many Configuration Lookup

If your configuration-key contract ignores case and the settings are built once and read frequently, a frozen dictionary is an option. It is not necessary merely to get case-insensitive matching; an ordinary dictionary can do that too.

Put this class in its own file:

using System.Collections.Frozen;
using System.Diagnostics.CodeAnalysis;

namespace StringDemo;

public sealed class ConfigParser
{
    private readonly FrozenDictionary<string, string> _settings;

    public ConfigParser(IEnumerable<KeyValuePair<string, string>> rawSettings)
    {
        _settings = rawSettings.ToFrozenDictionary(
            pair => pair.Key,
            pair => pair.Value,
            StringComparer.OrdinalIgnoreCase);
    }

    public string? Get(string key) =>
        _settings.TryGetValue(key, out var value) ? value : null;

    public bool TryGet(string key, [NotNullWhen(true)] out string? value) =>
        _settings.TryGetValue(key, out value);
}

This wrapper assumes trusted configuration input, non-null values, and keys that are unique under the chosen comparer. Define how duplicates should be handled at your ingestion boundary rather than treating two differently cased spellings as independent keys.

FrozenDictionary is immutable and optimized for infrequent construction with frequent lookups. Construction has a cost. Keep a regular dictionary for changing settings, and measure your workload before presenting frozen storage as a performance improvement.


Practical Example: HTTP Field Names, Not All Field Values

HTTP field names are case-insensitive. A dictionary can model that lookup:

var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
    ["Content-Type"] = "application/json",
    ["X-Correlation-Id"] = "AbC123"
};

Console.WriteLine(headers["content-type"]);
Console.WriteLine(headers["CONTENT-TYPE"]);
Console.WriteLine(headers["x-correlation-id"]);

Expected output: application/json, application/json, AbC123.

The comparer applies to keys, not values. Each field defines how to interpret its value; don't lowercase every header value.

This dictionary is a comparison example, not a complete HTTP-header implementation. Real headers can have multiple values and field-specific combination rules. In an HTTP application, use the framework's header collection rather than replacing it with a custom single-value parser.


.NET 10+: CompareOptions.NumericOrdering

Numeric ordering lets a culture comparer treat digit sequences by numeric value. It was introduced in .NET 10; it is not a general change to the default comparison rules.

using System.Globalization;

string[] files = { "file10.txt", "file2.txt", "file1.txt", "file20.txt" };

var ordinal = files.Order(StringComparer.Ordinal).ToArray();
var numericComparer = StringComparer.Create(
    CultureInfo.GetCultureInfo("en-US"),
    CompareOptions.NumericOrdering);
var numeric = files.Order(numericComparer).ToArray();

Console.WriteLine(string.Join(", ", ordinal));
Console.WriteLine(string.Join(", ", numeric));
Console.WriteLine(numericComparer.Equals("file02.txt", "file2.txt"));

Expected output, with globalization support:

file1.txt, file10.txt, file2.txt, file20.txt
file1.txt, file2.txt, file10.txt, file20.txt
True

That final result matters if you reuse the comparer in a set or dictionary: leading zeros may no longer distinguish keys.

The option's contract is about sequences of decimal digits. Signs and decimal points terminate a digit sequence. Don't use it as a decimal-number parser or a semantic-version comparer.

Numeric ordering is for comparison and sorting, not index-based matching. The documented unsupported operations are IndexOf, LastIndexOf, StartsWith, EndsWith, IsPrefix, and IsSuffix. Ordinary case-insensitive sorting doesn't enable this option automatically.


Applying Comparison Rules in Application Code

When working with C# enumerations, distinguish parsing string input into an enum from converting an enum value back to text. The C# Enum to String guide covers the conversion side.

When matching names in a plugin architecture, define whether plugin identifiers are case-sensitive before selecting the dictionary comparer. Either ordinal option avoids making those identities depend on the user's language.

When a caching service wraps another service through the decorator pattern, use a key comparer that matches the cache-key contract. An ignore-case comparer would be a bug if differently cased keys identify different resources.

When organizing command handlers with feature slicing in C#, apply the identifier contract consistently wherever commands are matched. Choose case-insensitive lookup only if those command names are defined to ignore case.


Summary: Rules of Thumb

  1. Use equality APIs for equality and ordering APIs for sorting.
  2. For non-linguistic strings, choose between Ordinal and OrdinalIgnoreCase according to the actual case-sensitivity contract.
  3. Use an appropriate culture for linguistic matching and display sorting.
  4. Prefer explicit comparison overloads; string == is already clear when ordinal, case-sensitive equality is intended.
  5. Give dictionaries and sets the comparer they need instead of lowercasing each lookup.
  6. Use spans when you need to compare a slice without constructing a substring.
  7. Keep URL components, filesystem identity, Unicode normalization, and numeric ordering distinct from basic ignore-case matching.

FAQ

What is the difference between Ordinal and OrdinalIgnoreCase?

Ordinal uses case-sensitive, non-linguistic comparison of UTF-16 code units. OrdinalIgnoreCase uses case-insensitive ordinal rules, independent of the current culture. Neither performs Unicode normalization for you.

Should I avoid == for string comparison?

Not when ordinal, case-sensitive equality is intended and the operands are strings. Use string.Equals with an appropriate StringComparison when you need ignore-case or linguistic rules. Be aware that operands typed as object can select different operator behavior.

Is string.Compare the same as string.Equals?

No. string.Compare returns an ordering result and its two-string overload uses the current culture. string.Equals returns a Boolean and its two-string overload uses ordinal equality. Choose explicit rules when the distinction matters, and don't assume comparison results are restricted to -1, 0, and 1.

When should I use CurrentCulture or InvariantCulture?

Use the current or a deliberately selected culture for linguistic text. Invariant culture is also linguistic; it isn't a default for every stored string. For symbolic identifiers, start with ordinal rules and choose whether case matters.

What is the Turkish i problem?

Turkish casing maps lowercase i to uppercase \u0130, not ASCII I. That is correct for Turkish text but can break a symbolic comparison implemented by current-culture casing. Ordinal ignore-case comparison avoids selecting Turkish linguistic rules for those identifiers.

How do I make a case-insensitive dictionary in C#?

Pass StringComparer.OrdinalIgnoreCase to its constructor when your key contract ignores case. Use the same rule for related sets and lookups. A frozen dictionary is an optional read-many storage choice, not a requirement for case-insensitive matching.

Does OrdinalIgnoreCase make whole URLs or file paths equivalent?

No. URI components have different rules, and file identity depends on the filesystem and path resolution. Select comparison rules for the specific component or identifier you are actually handling.

Does ignoring case give me natural numeric sorting?

No. On .NET 10+, explicitly choose CompareOptions.NumericOrdering through a suitable culture comparer when digit-sequence ordering is the requirement. It isn't a semantic-version parser and doesn't work for index-based searches.

An error has occurred. This application may no longer respond until reloaded. Reload