C# String Equals()

In C#, the Equals() method is used to compare two strings for equality. The method returns a Boolean value indicating whether the two strings are equal or not. Here’s the general syntax:

string str1 = "Hello";
string str2 = "World";

bool areEqual = str1.Equals(str2);

In the example above, the Equals() method is called on the str1 string and passed str2 as an argument. The method compares the content of the two strings and returns true if they are equal and false otherwise.

It’s important to note that the Equals() method performs a case-sensitive comparison by default. If you want to perform a case-insensitive comparison, you can use the Equals() method overload that accepts a StringComparison parameter:

string str1 = "Hello";
string str2 = "hello";

bool areEqual = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);

In this case, the StringComparison.OrdinalIgnoreCase argument specifies a case-insensitive comparison. The method will return true because the content of the two strings is the same, regardless of the case.

Keep in mind that if either of the strings being compared is null, the Equals() method will return false without throwing an exception. If you want to handle null strings appropriately, you can use the String.Equals() static method, which can handle null values:

string str1 = null;
string str2 = "Hello";

bool areEqual = String.Equals(str1, str2);

In this case, the String.Equals() method returns false because str1 is null and str2 is not null.

That’s a brief overview of using the Equals() method in C# to compare strings. Remember to choose the appropriate comparison method based on your specific requirements, such as case-sensitivity or handling null values.

C# String Equals() Method Example:

Certainly! Here’s an example that demonstrates the usage of the Equals() method in C#:

using System;

class Program
{
    static void Main()
    {
        string str1 = "Hello";
        string str2 = "World";
        string str3 = "Hello";

        bool areEqual1 = str1.Equals(str2);
        bool areEqual2 = str1.Equals(str3, StringComparison.OrdinalIgnoreCase);

        Console.WriteLine("str1.Equals(str2): " + areEqual1);
        Console.WriteLine("str1.Equals(str3, StringComparison.OrdinalIgnoreCase): " + areEqual2);
    }
}

Output:

str1.Equals(str2): False
str1.Equals(str3, StringComparison.OrdinalIgnoreCase): True

In this example, we have three strings: str1, str2, and str3.

The str1.Equals(str2) comparison returns false because the content of str1 and str2 is different.

The str1.Equals(str3, StringComparison.OrdinalIgnoreCase) comparison returns true because we’re using the StringComparison.OrdinalIgnoreCase option, which performs a case-insensitive comparison. Thus, the content of str1 and str3 is considered equal, regardless of the difference in case.

I hope this example helps you understand the usage of the Equals() method in C#. Let me know if you have any further questions!