C# Equals Error

CipherIS used Ask the Experts™
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?
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
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.

Top Expert 2009

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