In this article, we are going to discuss the difference between Equality Operator ( ==) and Equals() method
Generally both we used to compare the value type and reference type data. The main difference between the Equality Operator and Equals() Method is equality operator compares the reference and the Equals() method compares the content.
let’s discuss in detail with examples
In the first example, we can compare the two strings.
Example:
namespace EqualsOpertor
{
class Program
{
static void Main(string[] args)
{
string FName = "Sam";
string FName1 = "Sam";
//Equality Operator
Console.WriteLine("Equality Operator (==) Result {0}", FName == FName1);
//Equals() Method
Console.WriteLine("Equals() Method Result {0}" , FName.Equals(FName1));
Console.ReadLine();
}
}
}
Output:
In the below example we can compare the content of the string but references of both the variables are different. The equality operator will return a false result but Equals() method returns the true result because it compares the content of the strings.
Example:
namespace EqualsOpertor
{
class Program
{
static void Main(string[] args)
{
string FName = "Sam";
char [] ArrData = {'S','a','m'};
object FName1 = new string(ArrData);
//Equality Operator
Console.WriteLine("Equality Operator (==) Result {0}", FName == FName1);
//Equals() Method
Console.WriteLine("Equals() Method Result {0}" , FName.Equals(FName1));
Console.ReadLine();
}
}
}
Output:
We can check one more example and assigned a null value to the variable and check how it behaves in runtime.
namespace EqualsOpertor
{
class Program
{
static void Main(string[] args)
{
string FName = "Sam";
string FName1 = null;
//Equality Operator
Console.WriteLine("Equality Operator (==) Result {0}", FName == FName1);
//Equals() Method
Console.WriteLine("Equals() Method Result {0}" , FName1.Equals(FName));
Console.ReadLine();
}
}
}
Output:
FName1 value is null due to that we got an exception, Equals() Method never worked in the null value condition so the use of equals operator is very easy that Equals() Method but the condition is the Type of both sides should be same else we will get a compile-time error.
The main difference is one is used to compare the reference of variables and the other is used to compare the content of variables, depending on the requirement we can take a call.
Need help?
Read this post again, if you have any confusion or else add your questions in Community