Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between “Equals” and “SequenceEqual”?

Tags:

Is there any cases in which:

Equals(MyList1, MyList2) != MyList1.SequenceEqual(MyList2);

And what is the difference between:

Equals(obj1, obj2) and obj1.Equals(obj2)

Thanks.

like image 470
CloudyMarble Avatar asked May 09 '12 06:05

CloudyMarble


People also ask

What is SequenceEqual?

SequenceEqual<TSource>(IEnumerable<TSource>, IEnumerable<TSource>) Determines whether two sequences are equal by comparing the elements by using the default equality comparer for their type.

How SequenceEqual works?

SequenceEqual() method If the two sequences contain the same number of elements, and each element in the first sequence is equal to the corresponding element in the second sequence (using the default equality comparer) then SequenceEqual() returns true . Otherwise, false is returned.

Does SequenceEqual check order?

The SequenceEqual method checks whether the number of elements, value of each element and order of elements in two collections are equal or not.

What is the difference between equality operator and equals () method in C #?

The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.


2 Answers

Equals returns true only if MyList1 and MyList2 are the same instance.
SequenceEqual returns true if both lists contain the same items.

Example:

var list1 = new List<int> { 1, 2, 3 };
var list2 = new List<int> { 1, 2, 3 };
var list3 = list1;
var list4 = new List<int> { 1, 2, 3, 4 };

Equals(list1, list2) == false
list1.SequenceEqual(list2) == true

Equals(list1, list3) == true
list1.SequenceEqual(list3) == true

Equals(list1, list4) == false
list1.SequenceEqual(list4) == false

The difference between Equals(obj1, obj2) and obj1.Equals(obj2) is that the first one uses the static method Object.Equals and the second uses the instance method Equals. The result of these two calls will differ, if the class of obj1 overrides Object.Equals.

like image 86
Daniel Hilgarth Avatar answered Sep 23 '22 03:09

Daniel Hilgarth


For 2nd part of question as first has been answered by @Daniel:

Equals(obj1, obj2) and obj1.Equals(obj2)

obj1.Equals(obj2) is instance method of object and it will throw exception if obj1 is null. Where as Equals(obj1,obj2) is static method and will work if you obj1 is null. You can also override Euqals for a class

object obj1 = new object();
object obj2 = new object();
Console.WriteLine(obj1.Equals(obj2)); //print false
obj1 = null;
Console.WriteLine(obj1.Equals(obj2)); // will throw exception
Console.WriteLine(Equals(obj1, obj2));// return false in this case and since its static it will not throw the exception
like image 44
Habib Avatar answered Sep 24 '22 03:09

Habib