How to check if two strings are equal in C#

Overview

The Equals() method can be used to check if two strings are equal in C#. Two strings are considered equal if they have the same string values. The Equals() method returns True if the two strings are equal. Otherwise, it returns False.

Syntax

string1.Equals(string2);

Parameters

  • string1: The first string to be checked.

  • string2: The second string to be checked.

Return value

The return value is a boolean. The Equals() method returns True if the strings are equal, and False if they are not.

Code example

In the code example below, we define and initialize several strings. Then, we use the Equals() method to check if some of them are equal.

// create our class
class StringEquality
{
// main method
static void Main()
{
// define and initialize string variables
string string1 = "Google";
string string2 = "Meta";
string string3 = "Facebook";
string string4 = "Meta";
// check if strings are equal
bool a = string1.Equals(string2);
bool b = string2.Equals(string4);
bool c = string3.Equals(string4);
bool d = string4.Equals(string2);
// print returned values
System.Console.WriteLine(a);
System.Console.WriteLine(b);
System.Console.WriteLine(c);
System.Console.WriteLine(d);
}
}

As we can see in the code above, True is printed for strings whose values are the same, and False is printed for values that are not equal.

Free Resources