How to Compare Strings in C#: Syntax and Examples
In C#, you can compare strings using the
== operator, the Equals() method, or the String.Compare() method. The == operator checks if two strings have the same value, while Equals() can be used with options like case sensitivity. String.Compare() returns an integer indicating the lexical order of the strings.Syntax
Here are the common ways to compare strings in C#:
string1 == string2: Checks if both strings have the same value.string1.Equals(string2): Compares strings for equality, can specify case sensitivity.String.Compare(string1, string2): Returns an integer indicating order (<0, 0, >0).
csharp
bool areEqual = string1 == string2;
bool areEqualMethod = string1.Equals(string2);
int comparison = String.Compare(string1, string2);Example
This example shows how to compare strings using ==, Equals() with case sensitivity, and String.Compare().
csharp
using System; class Program { static void Main() { string a = "Hello"; string b = "hello"; // Using == operator Console.WriteLine(a == b); // False // Using Equals with case sensitivity Console.WriteLine(a.Equals(b)); // False // Using Equals ignoring case Console.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True // Using String.Compare int result = String.Compare(a, b, StringComparison.OrdinalIgnoreCase); if (result == 0) Console.WriteLine("Strings are equal ignoring case."); else if (result < 0) Console.WriteLine("a is less than b."); else Console.WriteLine("a is greater than b."); } }
Output
False
False
True
Strings are equal ignoring case.
Common Pitfalls
Common mistakes when comparing strings in C# include:
- Using
==when you need case-insensitive comparison. - Not specifying
StringComparisoninEquals()orCompare(), which defaults to case-sensitive and culture-sensitive comparison. - Using
ReferenceEquals()which checks if two variables point to the same object, not if their text is equal.
csharp
string x = "Test"; string y = "test"; // Wrong: case-sensitive comparison bool wrong = x == y; // false // Right: case-insensitive comparison bool right = x.Equals(y, StringComparison.OrdinalIgnoreCase); // true
Quick Reference
| Method | Description | Case Sensitivity |
|---|---|---|
| == operator | Checks if two strings have the same value | Case-sensitive |
| Equals() | Checks equality, can specify case sensitivity | Case-sensitive by default, can ignore case with parameter |
| String.Compare() | Compares lexical order, returns int (<0, 0, >0) | Case-sensitive by default, can ignore case with parameter |
Key Takeaways
Use == for simple, case-sensitive string equality checks.
Use Equals() with StringComparison to control case sensitivity.
Use String.Compare() to determine lexical order between strings.
Avoid ReferenceEquals() for string content comparison.
Always specify StringComparison to avoid culture and case issues.