C# `Char.Equals()`: Performing Case-Sensitive Character Comparisons
Learn how to use C#'s `Char.Equals()` method for efficient and case-sensitive character comparison. This tutorial explains its functionality, demonstrates its usage with code examples, and highlights its application in various string manipulation, character classification, and data validation tasks.
Using C#'s `Char.Equals()` Method for Character Comparison
The C# `Char.Equals()` method compares two characters for equality. It's a fundamental method for character manipulation and is often used in string processing or data validation.
`Char.Equals()` Syntax
public static bool Equals(char c1, char c2);
This static method takes two characters (`c1` and `c2`) as input and returns `true` if they are equal; otherwise, `false`.
Example 1: Basic Character Comparison
char char1 = 'A';
char char2 = 'A';
bool isEqual = Char.Equals(char1, char2); //isEqual will be true
Console.WriteLine(isEqual);
Case Sensitivity
The `Char.Equals()` method is case-sensitive. 'A' and 'a' are considered different characters.
Example 2: Case-Sensitive vs. Case-Insensitive Comparison
char char1 = 'a';
char char2 = 'A';
bool isEqual = Char.Equals(char1, char2); // false (case-sensitive)
bool isEqualIgnoreCase = char.ToLower(char1) == char.ToLower(char2); // true (case-insensitive)
Console.WriteLine($"Case-sensitive: {isEqual}");
Console.WriteLine($"Case-insensitive: {isEqualIgnoreCase}");
Unicode Character Comparison
C# uses Unicode to represent characters. `Char.Equals()` considers the Unicode values when comparing characters.
Example 3: Unicode Comparison
char char1 = '\u00E9'; // é (Unicode)
char char2 = 'é'; // é (Latin small letter e with acute)
bool isEqual = Char.Equals(char1, char2); // true
Console.WriteLine(isEqual);
String Comparison Using `String.Equals()`
Similar to `Char.Equals()`, the `String.Equals()` method is used to compare strings. You can use `StringComparison.OrdinalIgnoreCase` for a case-insensitive comparison.
string str1 = "Hello";
string str2 = "hello";
bool isEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase); // true
Console.WriteLine(isEqual);