简体   繁体   中英

Whats the difference between these two comparison statements?

Whats the difference between these two comparison statments?

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

Obviously the aim is to test whether the object '@this' isnull.

Well it depends on the type of @this . If it doesn't have an overload of == , the second line will just perform a direct reference comparison, whereas the first line will call an overridden Equals method or an implementation of IEquatable.Equals .

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

The first statement calls the Equals() method between objects to see if their values are equal, assuming it has been overriden and implemented in the class T . The second statement compares the references instead, unless the == operator has been overridden like in the String class.

operator == calls ReferenceEquals on comparing objects, so compare that objects are pointing to the same memory location.

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

For example, for CLR string Equals compares content of a string and not a reference , even if string is a reference type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM