This is a common question, and I am sure that many of you confused about which one to use. Actually someday you can run into a big trouble by using them wrong.
Let’s take a simple example to demonstrate the behaviors of two comparisons.
char[] test = {'t','e','s','t'};
string x = "test";
string y = new string (test);
object ox=x;
object oy=y;
Console.WriteLine(x==y);
Console .WriteLine(ox==oy);
Console.WriteLine(x.Equals(y));
Console.WriteLine(ox.Equals(oy));
When you run this application, you will notice that the first about is true, but the second one is false. but more confusing that third and the fourth statements are both true.
Ok let's see the trick in this. == operator on strings, compares strings by content. But == operator on objects just checks if the objects are same. So the first statement is true because both strings contain "test" as content, and the second one is false, because they are not the same object at all.
But what about third and the fourth, why == operator states false but Equals method states true. The answer is "Operators are not applied polymorphically, methods are." As ox and oy are objects holding strings, running Equals method on both, actually runs Equals method on strings.
Let's see objects Equals definition from dotnet framework.
public static bool Equals(object objA, object objB)
{
if (objA == objB)
{
return true;
}
if ((objA != null) && (objB != null))
{
return objA.Equals(objB);
}
return false;
}
As we see if both objects are not reference equal, then objects are compared with their type in mind.
Hope this helps a little to clarify difference between == operator and Equals method.
Answered by
Mohd Farooq
, an ibibo Master,
at
6:34 PM on June 01, 2008