Question is raised by Sharath kumar by sending mail to dotnetcircle@gmail.com.
What is difference between == and .Equals?
My Answer:
When == is used on an object type, it'll resolve to System.Object.ReferenceEquals.
Equals is just a virtual method and behaves as such, so the overridden version will be used (which, for string type compares the contents).
Let's see by example:
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
using System;
namespace ComparisionExample
{
class Program
{
static void Main(string[] args)
{
string name = "dotnetcircle";
string myName = name;
Console.WriteLine("== operator result is {0}", name == myName);
Console.WriteLine("Equals method result is {0}", name.Equals(myName));
Console.ReadKey();
}
}
}
o/p:
== operator result is True
.Equals method result is True
Let’s see another example where the contents will be the same in both object variables but both have different references. So the == Operator returns False because it compares the reference identity while the Equals() method returns True because it compares the contents of the objects.
using System;
namespace ComparisionExample
{
class Program
{
static void Main(string[] args)
{
object name = "dotnet";
char[] values = {'d','o','t','n','e','t'};
object myName = new string(values);
Console.WriteLine("== operator result is {0}", name == myName);
Console.WriteLine("Equals method result is {0}", myName.Equals(name));
Console.ReadKey();
}
}
}
o/p:
== operator result is false
Equals method result is false.
For more clear,
StringBuilder s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True
s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).
Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one your class inherits by default) compares identity, i.e. it's the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class - its operator== compares value rather than identity.
If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it's simply too ambiguous.
Summary:
Do you know more clear answer? you can contribute with your answer in this blog by sending mail to dotnetcircle@gmail.com.
No comments:
Post a Comment