I thought calling Equals() on two empty Lists would return true, but that's not the case. Could someone explain why?
var lst = new List<Whatever>();
var lst2 = new List<Whatever>();
if(!lst.Equals(lst2))
throw new Exception("seriously?"); // always thrown
Because Equals
is checking for references - lst
and lst2
are different objects. (note that Equals is inherited from Object
and not implemented in List<T>
)
You're looking for Linq's SequenceEquals
.
Even when using SequenceEquals
, don't expect it to work with your Whatever
class on non-empty lists (unless it is a struct). You may want to implement a comparer, and use the right overload.
Equals
here is comparing reference of two lists which would be different because they are separate lists and that's why it will always be false in this case.
Object documentation (MSDN documentation):
The default implementation of Equals supports reference equality for reference types, and bitwise equality for value types. Reference equality means the object references that are compared refer to the same object. Bitwise equality means the objects that are compared have the same binary representation.
List documentation (MSDN documentation):
Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
You have two different objects (two times new ...) so there not the same.
Because it compares on object identity, not the contents of the list. They are two separate objects.
See this answer from the C# FAQ.
The Equals
implementation of List<T>
is the inherited one from Object
:
The default implementation of Equals supports reference equality for reference types
In other words, since these are two different lists, they have different references, so Equals
returns false
.
List<T>.Equals()
will compare the references of the two lists and return true if they are equal. If you want to compare the elements of two lists, use List<T>.SequenceEquals()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With