The static String.Compare() method compares two strings and tells you which comes first in sort order. It returns an int—not a bool—making it ideal for sorting names, validating order, and building comparison logic with optional case and culture rules.
01
Static Method
Call on String class.
02
int Return
< 0, 0, or > 0.
03
Sort Order
Lexicographic compare.
04
ignoreCase
Case-insensitive option.
05
StringComparison
Modern overload.
06
vs Equals()
Order vs equality.
Fundamentals
Definition and Usage
In C#, String.Compare(string strA, string strB) is a static method that evaluates two strings character by character and reports their relative lexicographic order—the same ordering a dictionary or phone book uses.
The return value is an int: a negative number when strA comes before strB, zero when they compare as equal under the chosen rules, and a positive number when strA comes after strB. This three-way result is what sorting algorithms and Array.Sort expect.
💡
Beginner Tip
Do not write if (string.Compare(a, b)) when you mean “are equal.” A result of -1 is truthy in some contexts but means less than, not equal. Always compare explicitly: == 0 for equality, < 0 for less-than.
Foundation
📝 Syntax
Common overloads declared on System.String:
C#
public static int Compare(string strA, string strB);
public static int Compare(string strA, string strB, bool ignoreCase);
public static int Compare(string strA, string strB, StringComparison comparisonType);
Parameters
strA, strB — the two strings to compare (either may be null; null sorts before non-null).
ignoreCase — when true, letter case is ignored using culture-sensitive rules.
comparisonType — a StringComparison value such as Ordinal, OrdinalIgnoreCase, or CurrentCultureIgnoreCase.
Return Value
< 0 → strA is less than strB
0 → strA equals strB (under chosen rules)
> 0 → strA is greater than strB
Cheat Sheet
⚡ Quick Reference
Strings
Call
Result
"apple", "banana"
Compare(a, b)
< 0 (apple first)
"hello", "hello"
Compare(a, b)
0 (equal)
"Z", "a"
Compare(a, b)
< 0 (Z before a in code order)
"Hello", "hello"
Compare(a, b, true)
0 (ignore case)
"file.txt", "FILE.TXT"
Compare(a, b, OrdinalIgnoreCase)
0
Basic
string.Compare(a, b)
Culture-sensitive
Equal?
Compare(a, b) == 0
Equality test
Ignore case
Compare(a, b, true)
bool overload
Modern
Compare(a, b, StringComparison.OrdinalIgnoreCase)
Recommended
Hands-On
Examples Gallery
Run with dotnet run. Each example builds practical comparison skills from basic ordering to sorting and modern StringComparison usage.
📚 Getting Started
Compare two strings and interpret the integer result.
Example 1 — Basic Compare() Usage
Compare "apple" and "banana". Because 'a' < 'b', apple comes first and the result is negative.
C#
using System;
class Program {
static void Main() {
int result = string.Compare("apple", "banana");
Console.WriteLine($"Compare result: {result}");
if (result < 0) {
Console.WriteLine("\"apple\" comes before \"banana\"");
} else if (result > 0) {
Console.WriteLine("\"apple\" comes after \"banana\"");
} else {
Console.WriteLine("Strings are equal");
}
}
}
📤 Output:
Compare result: -1
"apple" comes before "banana"
How It Works
The default overload uses culture-sensitive, case-sensitive rules. The exact negative number (often -1) indicates ordering; what matters is the sign, not the specific value.
Example 2 — Comparing Equal Strings
When both strings have identical content under the comparison rules, Compare() returns 0.
C#
using System;
class Program {
static void Main() {
string a = "hello";
string b = "hello";
int result = string.Compare(a, b);
Console.WriteLine($"Result: {result}");
Console.WriteLine($"Equal: {result == 0}");
Console.WriteLine($"Same as == : {a == b}");
}
}
📤 Output:
Result: 0
Equal: True
Same as == : True
How It Works
A return value of 0 means the strings compare as equal. For simple equality checks, a == b or string.Equals(a, b) is clearer—use Compare() when you also need less-than or greater-than information.
📈 Practical Patterns
Case rules, StringComparison, and sorting.
Example 3 — Case-Sensitive vs Case-Insensitive
Pass true as the third argument to ignore letter case using culture-sensitive rules.
C#
using System;
class Program {
static void Main() {
string a = "Hello";
string b = "hello";
int sensitive = string.Compare(a, b);
int insensitive = string.Compare(a, b, ignoreCase: true);
Console.WriteLine($"Case-sensitive: {sensitive}");
Console.WriteLine($"Case-insensitive: {insensitive}");
}
}
📤 Output:
Case-sensitive: -1
Case-insensitive: 0
How It Works
With default rules, uppercase 'H' and lowercase 'h' are different characters, so the result is non-zero. With ignoreCase: true, the strings compare as equal and the method returns 0.
Example 4 — StringComparison Overload
The recommended modern overload makes comparison intent explicit—ideal for file names, keys, and protocol identifiers.
C#
using System;
class Program {
static void Main() {
string path1 = "Report.PDF";
string path2 = "report.pdf";
int ordinal = string.Compare(
path1, path2, StringComparison.Ordinal);
int ignoreCase = string.Compare(
path1, path2, StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"Ordinal: {ordinal}");
Console.WriteLine($"OrdinalIgnoreCase: {ignoreCase}");
}
}
📤 Output:
Ordinal: -1
OrdinalIgnoreCase: 0
How It Works
StringComparison.Ordinal compares raw Unicode code units without culture rules—fast and predictable. OrdinalIgnoreCase adds case insensitivity, a common choice for file extensions and configuration keys.
Example 5 — Sort Strings with Compare()
Use Compare() as the heart of a custom sort—or rely on Array.Sort, which uses similar comparison logic internally.
C#
using System;
class Program {
static void Main() {
string[] names = { "Charlie", "alice", "Bob" };
Array.Sort(names, StringComparer.OrdinalIgnoreCase);
Console.WriteLine("Sorted names:");
foreach (string name in names) {
Console.WriteLine($" {name}");
}
}
}
📤 Output:
Sorted names:
alice
Bob
Charlie
How It Works
Array.Sort with StringComparer.OrdinalIgnoreCase applies the same comparison rules as string.Compare(..., StringComparison.OrdinalIgnoreCase). Sorting is one of the most common real-world uses of string comparison.
Applications
🚀 Common Use Cases
Sorting lists — order user names, product titles, or file names alphabetically.
Range checks — verify a value falls between two string bounds (e.g., date strings in yyyy-MM-dd format).
Custom comparers — implement IComparer<string> using Compare() for collections.
Case-insensitive lookup keys — match dictionary keys or HTTP headers without caring about case.
Branching logic — choose actions based on whether one string precedes another in order.
🧠 How Compare() Works
1
You pass two strings
Optionally specify case and culture rules via ignoreCase or StringComparison.
Input
2
Characters are compared left to right
The runtime walks both strings from the start until a difference appears or one string ends.
Scan
3
First mismatch decides order
If all compared characters match and lengths are equal, the result is 0. Otherwise the differing character (or length) determines the sign.
Decision
=
📊
int result returned
Negative, zero, or positive—ready for if branches, sorting, or equality checks with == 0.
Important
📝 Notes
Compare() returns int, not bool—check == 0 for equality.
The default overload is culture-sensitive—sort order can vary by locale.
Prefer StringComparison.Ordinal or OrdinalIgnoreCase for internal keys, paths, and identifiers.
null is treated as less than any non-null string; two null values compare as equal (0).
For instance-style comparison, use strA.CompareTo(strB)—same sign convention.
When you only need equality, string.Equals(a, b, comparison) or a == b reads more clearly.
Performance
⚡ Optimization
StringComparison.Ordinal comparisons are faster than culture-sensitive comparisons because they skip locale-specific rules. For high-volume sorting or hashing of internal strings, prefer ordinal modes. Avoid calling Compare() repeatedly on the same pair inside tight loops—cache the result or pre-sort once. For large collections, use built-in Array.Sort or LINQ OrderBy with an appropriate StringComparer rather than hand-written bubble sorts.
Wrap Up
Conclusion
The C# Compare() method is a fundamental tool for string ordering. It returns a signed integer that tells you which string comes first, whether they are equal, or which comes last—with optional control over case and culture through overloads and StringComparison.
Practice the examples until reading < 0, 0, and > 0 feels natural, then explore CompareOrdinal() for culture-independent comparisons.
Use StringComparison overloads for explicit intent
Write Compare(a, b) == 0 for equality checks
Pick OrdinalIgnoreCase for file names and keys
Use StringComparer when sorting arrays and lists
Handle null before comparing if your logic requires it
❌ Don’t
Treat the int result as a boolean for equality
Assume the exact value is always -1 or 1 (sign matters)
Use culture-sensitive compare for internal protocol strings
Use Compare() when Equals() alone is enough
Forget that case-sensitive "A" and "a" differ
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about Compare()
Use these points whenever you compare strings in C#.
5
Core concepts
📊01
Static Method
string.Compare(a, b)
Basics
🔢02
int Return
< 0, 0, or > 0.
Return
📝03
Sort Order
Lexicographic rules.
Concept
🔄04
ignoreCase
Case-insensitive option.
Overload
⚡05
StringComparison
Modern best practice.
API
❓ Frequently Asked Questions
String.Compare() is a static method that compares two strings lexicographically (dictionary order). It returns an int: negative if the first string comes before the second, zero if they are equal under the chosen rules, and positive if the first comes after the second.
Call it on the String class: string.Compare(strA, strB). Common overloads add bool ignoreCase or StringComparison comparisonType. Example: string.Compare("apple", "banana") or string.Compare("A", "a", StringComparison.OrdinalIgnoreCase).
It returns int—not bool. Less than 0 means strA sorts before strB, 0 means they compare as equal, greater than 0 means strA sorts after strB. To test equality, write if (string.Compare(a, b) == 0) or prefer string.Equals(a, b).
Use string.Compare(a, b, true) for culture-sensitive ignore-case, or the modern overload string.Compare(a, b, StringComparison.OrdinalIgnoreCase) when you want a fast, culture-independent check (common for identifiers and file names).
Compare() returns ordering information (negative, zero, or positive) and is ideal for sorting. Equals() returns bool—true or false—for equality checks. Use Compare() or CompareTo() when order matters; use Equals() or == when you only need same-or-different.
Compare() uses culture-aware rules by default (letter order can vary by language). CompareOrdinal() compares raw Unicode code units without culture rules—faster and predictable. Use Compare() for user-facing sorted lists; use CompareOrdinal() for internal identifiers and paths.
Did you know?
Array.Sort(strings) and LINQ’s OrderBy rely on the same comparison contract as String.Compare(): return negative when the first item is smaller, zero when equal, positive when greater. That is why learning Compare() helps you understand sorting throughout .NET.