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.
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.
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.
The SequenceEqual method checks whether the number of elements, value of each element and order of elements in two collections are equal or not.
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.
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
.
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
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