What is the difference between these two comparisons?

What is the difference between these two comparisons?

var result = EqualityComparer<T>.Default.Equals(@this, null); var result = @this == null; 

Obviously, the goal is to check if the object '@this' isnull.

+4
source share
3 answers

operator == calls ReferenceEquals when comparing objects, so compare that the objects point to the same place in memory.

Equals instead is just a virtual method, so it can behave differently for different types, since it can be overridden.

For example, for the CLR, string Equals compares the contents of a string , not the link, even if string is a reference type.

+1
source

Well, that depends on the type of @this . If it does not have overload == , the second line will simply do a direct comparison of the links, while the first line will call an overridden Equals method or an implementation of IEquatable.Equals .

Any reasonable implementation will give the same result for both comparisons.

+7
source

The first statement calls the Equals () method between objects to make sure their values ​​are equal, assuming it has been overridden and implemented in class T The second statement compares the links instead, if the == operator has not been redefined, as in the String class.

+2
source

Source: https://habr.com/ru/post/1434011/


All Articles