We compare strings to check if they are the same or to find their order. This helps us decide things like if two words match or which word comes first in a list.
0
0
String comparison and equality in C Sharp (C#)
Introduction
Checking if a user entered the correct password.
Sorting a list of names alphabetically.
Finding if a word exists in a sentence.
Comparing two file names to see if they are identical.
Syntax
C Sharp (C#)
bool result = string1 == string2;
bool resultIgnoreCase = string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);
int compareResult = string.Compare(string1, string2, StringComparison.Ordinal);Use == or string.Equals to check if two strings are exactly equal.
Use string.Compare to find which string comes first alphabetically.
Examples
Checks if two strings are exactly the same.
C Sharp (C#)
string a = "hello"; string b = "hello"; bool isEqual = a == b; // true
Checks equality ignoring uppercase or lowercase differences.
C Sharp (C#)
string a = "Hello"; string b = "hello"; bool isEqualIgnoreCase = string.Equals(a, b, StringComparison.OrdinalIgnoreCase); // true
Compares two strings alphabetically. Negative means
a comes before b.C Sharp (C#)
string a = "apple"; string b = "banana"; int result = string.Compare(a, b, StringComparison.Ordinal); // negative number
Sample Program
This program compares two strings in three ways: exact match, ignoring case, and alphabetical order.
C Sharp (C#)
using System; class Program { static void Main() { string word1 = "Cat"; string word2 = "cat"; bool equalExact = word1 == word2; bool equalIgnoreCase = string.Equals(word1, word2, StringComparison.OrdinalIgnoreCase); int compareResult = string.Compare(word1, word2, StringComparison.Ordinal); Console.WriteLine($"Exact equality: {equalExact}"); Console.WriteLine($"Equality ignoring case: {equalIgnoreCase}"); Console.WriteLine($"Compare result: {compareResult}"); } }
OutputSuccess
Important Notes
String comparison is case-sensitive by default.
Use StringComparison.OrdinalIgnoreCase to ignore case differences.
Compare returns 0 if strings are equal, less than 0 if first is before second, and greater than 0 if first is after second.
Summary
Use == or string.Equals to check if strings are equal.
Use string.Compare to find alphabetical order.
Ignore case by using StringComparison.OrdinalIgnoreCase.