what is difference "==" equals and ReferenceEquals

  • Thread starter Thread starter Guest
  • Start date Start date
Fei said:
Hi,

take string class as an example, who can explain the difference?

In the case of string, == will return true if both strings contain the
same value. ReferenceEquals returns true if both strings are the same
instance. Here is a code example:

string a = new string('a',3);
string b = new string('a',3);
string c = a;
Console.WriteLine(a==b); // True
Console.WriteLine(object.ReferenceEquals(a,b)); // False
Console.WriteLine(a==c); // True
Console.WriteLine(object.ReferenceEquals(a,c)); // True

In the case above, both a and b will contain the value "aaa". However
they are not the same instance. Both a and c will also contain the
value "aaa", but they are also the same instance.
 
Hi Fei Li,

Basically, == tests if object references point to the same object, and Equals() tests of object A has the same content as object B. For strings there isn't really a difference, because both == and Equals have been overriden to compare the content of the string.

Consider this:

public class MyClass1
{
private int i = 0;
public MyClass1(int value)
{
i = value;
}
}

public class MyClass2
{
private int i = 0;
public MyClass2(int value)
{
i = value;
}

public override bool Equals(object obj)
{
if(!(obj is MyClass2))
return false;

MyClass2 mc = (MyClass2)obj;
if(mc.i == this.i)
return true;
else
return false;
}

public override int GetHashCode()
{
return base.GetHashCode ();
}
}

MyClass1 A = new MyClass1(1);
MyClass1 B = new MyClass1(1);
MyClass2 C = new MyClass2(1);
MyClass2 D = new MyClass2(1);

A == B is false because A and B are references to different objects

A.Equals(B) is false because MyClass1 doesn't override Equals, so the base Object.Equals is used, which only compares references (==)

C == D is also false, same == operator, C and D are different references

C.Equals(D) is true because MyClass2 has overridden the default Equals method and implemented its own definition of equality. In this case C equals D if they are both MyClass2 and have the same value of 'i'. GetHashCode needs to be overriden of you override Equals.

string has not only overriden Equals to compare the content of the string, but also == to do the same.

Equals is meaningless unless you give it a meaning of your own.
 
Ah, ReferenceEquals, not Equals.

As Tom pointed out, using Equals for strings would not work since it would use the overriden method which compares the content. ReferenceEquals could then be used to determine if the strings really are the same strings and not just the same character sequence.
 
Back
Top