C# Equals Error

CipherIS
CipherIS used Ask the Experts™
on
Ok, I'm calling a class and set the following values.

UserKey v1 = new UserKey("John Doe", "JDOE");
UserKey v2 = new UserKey("John Doe", "JDOE");

The results when printing should be as follows
System.Console.WriteLine( v1.Equals(v1) ); // prints true
System.Console.WriteLine( v1.Equals(v2) ); // prints true

However, System.Console.WriteLine( v1.Equals(v2) ); PRINTS FALSE not TRUE.j

Why is this the case when both v1 and v2 have the same value?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Expert of the Quarter 2010
Expert of the Year 2010
Commented:
Unless you have an override method to re-implement Object.Equals, all it does is check the pointer.
If they are not pointing to the same object, even if all the content is the same, Equals returns false.

http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx
http://weblogs.asp.net/tgraham/archive/2004/03/23/94870.aspx
Top Expert 2009

Commented:
Objects of UserKey i.e. v1 and v2 are of reference type.
In case of reference type variable the variable holds the memory address i.e pointer on stack while data are store on heap
while in case of value type(primitive datatype) like integer,double,etc variable stores the actual value on stack.

So when you use Equals it compares the pointer not the data (value). If you want to compare values than you need to override Equals method of that class.
You should be overriding the GetHashCode() and Equals() method in UserKey class.

Basically the GetHashCode is used if you're going to use a Hashtable to store a list of UserKey objects and Equals method is used if you're going to check for existence in the list like ht.Contains(userKey1).

In general Object.Equals method is equivalent to Object.ReferenceEquals, that's why you're not getting consistent results. By overriding the default behavior (Equals method) you will be able to implement your own logic to determine if two objects are same or not.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial