Why are two empty lists not equal?

I thought that calling Equals () on two empty lists would return true, but that is not the case. Can someone explain why?

var lst = new List<Whatever>();
var lst2 = new List<Whatever>();
if(!lst.Equals(lst2))
    throw new Exception("seriously?"); // always thrown
+5
source share
11 answers

Equals This compares the link of the two lists, which will be different because they are separate lists and that in this case it will always be false.

+3
source

Because it Equalschecks links - lstand lst2- different objects. (note that Equals is inherited from Objectand not implemented in List<T>)

Linq SequenceEquals.
SequenceEquals , Whatever ( ). , .

+7

( MSDN):

Equals . , , . , .

( MSDN):

, . ( Object.)

( ...), .

+3

, . .

. #.

+2

Equals List<T> Object:

Equals

, , , Equals false.

+2

List<T>.Equals() true, . , List<T>.SequenceEquals()

+1

2 , equals , . List List. .

+1

.Equals on List - Object, , , . , .

0

, - ( ). . , , List, Equals

0

# .Net .

, , . integer, double, DateTime ..

, , :

int a = 10;
int b = 10;

if( a == b ) 
{
    // this will fire
}

, , :

int c = a;
c = c+5;

if( a == c ) 
{
    // this won't, because a==10 and c==15
}

- , . , , :

var a = new List<Whatever>();
var b = new List<Whatever>();
if( a == b ) 
{
    // this won't fire, a and be are separate objects
}

var c = a;
c.Add(new Whatever());
if( a == c ) 
{
    // this will, a and c are the same object.
    a[0]; // holds the value added to c
}

, , string.

0

, ( ).

You do not need to program well to understand this;) Suppose you have this and that , its not important what is inside this and that . It is simply important that this one is not , which or which is not this . This is what you check there withequals

-1
source

All Articles