Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are two empty Lists not Equal?

Tags:

c#

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
like image 865
Viet Norm Avatar asked Jan 11 '12 12:01

Viet Norm


6 Answers

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.

like image 108
Kobi Avatar answered Oct 27 '22 02:10

Kobi


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.

like image 29
Haris Hasan Avatar answered Oct 27 '22 03:10

Haris Hasan


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.

like image 42
Sascha Avatar answered Oct 27 '22 03:10

Sascha


Because it compares on object identity, not the contents of the list. They are two separate objects.

See this answer from the C# FAQ.

like image 39
Jeff Foster Avatar answered Oct 27 '22 03:10

Jeff Foster


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.

like image 2
Oded Avatar answered Oct 27 '22 02:10

Oded


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()

like image 1
Tomislav Markovski Avatar answered Oct 27 '22 02:10

Tomislav Markovski