The instance method CompareTo() compares the calling string to another and returns an int describing their lexicographic order. It implements IComparable<string>, which makes it the default comparison used when you sort lists and arrays of strings.
01
Instance Method
Call on a string.
02
int Return
< 0, 0, or > 0.
03
IComparable
Enables sorting.
04
Sort Order
Dictionary ordering.
05
Case-Sensitive
Default culture rules.
06
vs Compare()
Instance vs static.
Fundamentals
Definition and Usage
In C#, CompareTo(string value) is called on an existing string and compares it to value. The method walks both strings character by character using culture-sensitive rules and returns a signed integer describing which string comes first.
Unlike the static String.Compare() method, CompareTo() is an instance method—you write first.CompareTo(second), not String.CompareTo(first, second). Because String implements IComparable<string>, collections like List<string>.Sort() use CompareTo() automatically.
💡
Beginner Tip
Think of CompareTo() as asking “Where do I stand relative to this other string?” A negative answer means the caller comes first; zero means tie; positive means the other string comes first. For simple equality, == or Equals() is clearer than CompareTo() == 0.
Foundation
📝 Syntax
Two related signatures on System.String:
C#
public int CompareTo(string value);
public int CompareTo(object value); // IComparable implementation
Parameters
value — the string to compare against the current instance. May be null.
Return Value
< 0 → this string is less than value
0 → this string equals value
> 0 → this string is greater than value
Cheat Sheet
⚡ Quick Reference
Caller vs argument
Call
Result
"apple" vs "banana"
"apple".CompareTo("banana")
< 0
"hello" vs "hello"
"hello".CompareTo("hello")
0
"zebra" vs "apple"
"zebra".CompareTo("apple")
> 0
"Hello" vs "hello"
"Hello".CompareTo("hello")
< 0 (case-sensitive)
"text" vs null
"text".CompareTo(null)
> 0
Basic
strA.CompareTo(strB)
Instance compare
Equal?
a.CompareTo(b) == 0
Equality via compare
Static twin
string.Compare(a, b)
Same sign convention
Sort list
names.Sort()
Uses CompareTo()
Hands-On
Examples Gallery
Run with dotnet run. Each example builds practical skills from basic ordering to sorting, null handling, and comparison with the static Compare() method.
📚 Getting Started
Call CompareTo() on a string and interpret the result.
Example 1 — Basic CompareTo() Usage
Compare "apple" to "banana" using the instance method syntax.
C#
using System;
class Program {
static void Main() {
string str1 = "apple";
string str2 = "banana";
int result = str1.CompareTo(str2);
Console.WriteLine($"Comparison result: {result}");
if (result < 0) {
Console.WriteLine("\"apple\" comes before \"banana\"");
}
}
}
📤 Output:
Comparison result: -1
"apple" comes before "banana"
How It Works
str1.CompareTo(str2) compares from str1’s perspective: a negative result means str1 sorts before str2. This mirrors string.Compare(str1, str2).
Example 2 — Comparing Equal Strings
When content matches under the comparison rules, CompareTo() returns 0.
C#
using System;
class Program {
static void Main() {
string a = "C#";
string b = "C#";
int result = a.CompareTo(b);
Console.WriteLine($"CompareTo result: {result}");
Console.WriteLine($"Equals via == : {a == b}");
}
}
📤 Output:
CompareTo result: 0
Equals via == : True
How It Works
A zero result means the strings compare as equal. For readability, most code uses a == b instead of a.CompareTo(b) == 0 when only equality matters.
📈 Practical Patterns
Case sensitivity, sorting, and null arguments.
Example 3 — Case-Sensitive Comparison
By default, uppercase and lowercase letters are treated as different—CompareTo() does not ignore case on its own.
C#
using System;
class Program {
static void Main() {
string upper = "Hello";
string lower = "hello";
int compareToResult = upper.CompareTo(lower);
int staticIgnoreCase = string.Compare(
upper, lower, StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"CompareTo (case-sensitive): {compareToResult}");
Console.WriteLine($"Compare (OrdinalIgnoreCase): {staticIgnoreCase}");
}
}
'H' and 'h' differ under case-sensitive rules, so CompareTo() returns non-zero. For case-insensitive checks, use string.Compare with StringComparison or compare uppercased copies—avoid calling ToUpper() on null strings.
Example 4 — Sort a List with CompareTo()
List<string>.Sort() uses CompareTo() internally through IComparable<string>.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
List<string> names = new List<string> {
"Charlie", "alice", "Bob"
};
names.Sort();
Console.WriteLine("Sorted (default CompareTo):");
foreach (string name in names) {
Console.WriteLine($" {name}");
}
}
}
📤 Output:
Sorted (default CompareTo):
Charlie
alice
Bob
How It Works
Default sort order is case-sensitive and culture-aware. Uppercase letters sort before lowercase in many cultures, which is why "Charlie" appears first. Pass StringComparer.OrdinalIgnoreCase to Sort() when you need different rules.
Example 5 — Null Argument Handling
CompareTo treats null as less than any non-null string—the caller is considered greater.
C#
using System;
class Program {
static void Main() {
string text = "Hello";
int vsNull = text.CompareTo(null);
Console.WriteLine($"\"Hello\".CompareTo(null): {vsNull}");
Console.WriteLine("(Calling CompareTo on a null string throws NullReferenceException)");
}
}
📤 Output:
"Hello".CompareTo(null): 1
(Calling CompareTo on a null string throws NullReferenceException)
How It Works
Any non-null string compares greater than null (positive result). You cannot call an instance method on a null reference—null.CompareTo(...) throws NullReferenceException. Guard the caller with a null check before comparing.
Applications
🚀 Common Use Cases
Sorting collections — default Sort() on lists and arrays of strings.
Ordered collections — SortedSet<string> and SortedDictionary rely on comparison semantics.
Range validation — check whether a name falls between two bounds alphabetically.
Custom comparers — understand default behavior before wrapping with StringComparer.
IComparable patterns — mirror CompareTo when implementing your own comparable types.
🧠 How CompareTo() Works
1
You call on a string
this.CompareTo(other)—the current string is the left-hand side of the comparison.
Instance
2
Culture rules are applied
Characters are compared using the current culture’s sort rules unless you use a different API.
Compare
3
First difference sets the sign
Matching prefixes and equal length yield 0. Otherwise the first mismatched character (or length) decides.
Result
=
📊
int ordering returned
Feed into sort algorithms, conditional logic, or equality checks with == 0.
Important
📝 Notes
CompareTo() returns int, not bool—check signs explicitly.
Comparison is case-sensitive by default—"a" and "A" differ.
Uses current culture rules—sort order may vary by locale.
Equivalent to string.Compare(this, value) for the string overload.
For ordinal or explicit culture rules, prefer string.Compare with StringComparison.
Performance
⚡ Optimization
CompareTo() is efficient for typical string lengths. Avoid calling ToUpper() or ToLower() on every comparison in a sort loop—that allocates new strings repeatedly. Instead, pass StringComparer.OrdinalIgnoreCase to List.Sort(comparer) or use string.Compare with the appropriate StringComparison value once per comparison.
Wrap Up
Conclusion
The C# CompareTo() method is the instance-based way to compare string order. It powers default sorting through IComparable<string> and returns a signed integer you can use in algorithms and conditional logic.
Practice the examples until instance vs static comparison feels natural, then continue to Concat() for joining strings together.
Rely on default Sort() for simple alphabetical lists
Compare signs (< 0, == 0, > 0) explicitly
Use StringComparer when you need custom sort rules
Guard against null callers before invoking the method
❌ Don’t
Use CompareTo() == 0 when == reads clearer
Assume case-insensitive behavior by default
Call CompareTo on a null string reference
Convert to upper/lower on every compare in hot loops
Confuse instance CompareTo with static Compare
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about CompareTo()
Use these points whenever you compare strings in C#.
5
Core concepts
💬01
Instance Method
strA.CompareTo(strB)
Basics
🔢02
int Return
< 0, 0, or > 0.
Return
🚀03
IComparable
Powers default Sort().
Concept
🔒04
Case-Sensitive
Unless you override.
Rule
📝05
vs Compare()
Instance vs static.
API
❓ Frequently Asked Questions
CompareTo() is an instance method that compares the calling string to another string lexicographically. It returns int: negative if the current string comes before the argument, zero if equal, positive if it comes after. It implements IComparable<string> for sorting.
Call it on a string object: strA.CompareTo(strB). There is also CompareTo(object obj) from IComparable—pass another string (boxed as object) and cast is handled internally. Example: int result = "apple".CompareTo("banana");
It returns int—not bool. Less than 0 means the current string is less than the argument, 0 means equal under current culture rules, greater than 0 means greater. Use result == 0 for equality checks, or prefer == and Equals() for clarity.
Yes, by default. "apple" and "Apple" compare as different. CompareTo() uses culture-sensitive rules (current culture). For case-insensitive comparison, use string.Compare(a, b, true) or string.Compare with StringComparison.OrdinalIgnoreCase instead of CompareTo().
CompareTo() is an instance method: text.CompareTo(other). Compare() is static: string.Compare(a, b). Both return the same sign convention and support sorting, but Compare() offers overloads with StringComparison for explicit culture or ordinal rules.
If the argument is null, CompareTo returns a positive value (any non-null string is considered greater than null). If you call CompareTo on a null string reference, you get NullReferenceException—always ensure the calling string is not null.
Did you know?
When you call names.Sort() on a List<string>, the runtime uses string.CompareTo through the IComparable<string> interface. That is why learning CompareTo() helps you understand how .NET sorts strings everywhere—not just in code you write manually.