We can use both the equality operator (==) and Equals()
method to compare any two variables and return true if they are identical otherwise false. There are slight differences between them, other than one is the operator, and one is a method.
Like C/C++, the equality operator in C# compares any data type (int
, float
, double
) variables. It returns True
or False
. The usage is similar to other languages.
However, the equality operator behaves differently in the case of a string and objects. The equality operator checks if both objects are pointing to the same references or not, as the string is a reference type variable. This is called reference identity.
var1 == var2
var
and var2
are variables of the same data types.
Equals()
methodEvery datatype has implemented its Equals()
method. Its usage is to make a comparison between two variables. It only compares the data of the variables, unlike the equality operator, which behaves differently in the case of string and object. It returns True or False.
var.Equals(var2);
The var
and var2
are variables of any primitive data types.
Let's look at the code below:
class Educative{static void Main(){object str = "Educative";char[] values = {'E','d','u','c','a','t','i','v','e'};//typecasting array in string and storing it in str2 of object datatypeobject str2 = new string(values);System.Console.WriteLine("Equality operator output");System.Console.WriteLine(str==str2);System.Console.WriteLine("Equals() method output");System.Console.WriteLine(str.Equals(str2));System.Console.WriteLine("\n\n");//similary we can use int or other datatypeint num=5;int num2=10;int num3=5;System.Console.WriteLine("Equality operator output");System.Console.WriteLine(num==num2);System.Console.WriteLine(num==num3);System.Console.WriteLine("Equals() method output");System.Console.WriteLine(num.Equals(num2));System.Console.WriteLine(num.Equals(num3));}}
Line 5: We declare string str
and initialize it.
Line 6: We declare an array of char
type named values
.
Line 8: We allocate new memory and store the "Educative"
string.
Lines 10–13: We print the output string and the results of the comparison to the console.
Lines 19–29: We do the same as above with integers and print the results to the console after comparisons.
We get True
on the output in the case of string object for Equals()
method as the content of the variables is the same. But the output for the equality operator is False
as both variables point to different references despite having the same data.
When we compare integer variables, we get the expected output for both operator and method.
Free Resources