Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Contains compare objects differently than ==?

Tags:

c#

.net

Object t = 4;
Object s = 4;

if (t == s) {       // false
}

List<Object> q = new List<object>() { t };
Boolean found = q.Contains(s);          // found = true!

In the above code, I am not surprised by t == s returning false; it's comparing references to two objects and the references aren't the same.

But I am surprised the the Contains is returning true; obviously it's not just comparing object references..it's like it's comparing the unboxed values of 4 and 4..but how and why does it know to unbox the objects to compare them? I'm trying to understand the bigger pricniple at play here.

like image 651
Michael Ray Lovett Avatar asked Apr 23 '13 18:04

Michael Ray Lovett


People also ask

Can you compare objects with ==?

In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).

Why is it better to use is instead of ==?

== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.

Can you use == to compare objects in Java?

equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.

What is the difference between equals () and ==?

equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.


2 Answers

The expression

q.Contains(s)

is looking for an element of q for which EqualityComparer<object>.Default.Equals(element, s) is true. For boxed primitives, this compares the values.

like image 111
Sam Harwell Avatar answered Oct 26 '22 04:10

Sam Harwell


Contains, internally, is using the instance object.Equals method to compare the elements. It is not using the == operator.

The Equals method is virtual, whereas the == operator is static. This means that the == operator will determine which code to run based on the compile time type of the variable (and not the object at run time that the variable holds). A virtual method, on the other hand, is not statically bound. It determines which overload of Equals to run based on the run time type of the value the variable.

like image 44
Servy Avatar answered Oct 26 '22 03:10

Servy