Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a co-worker who's a fan of writing his null checks as follows:

if (!ReferenceEquals(myObject, null))

I, on the other hand, find this syntax cumbersome to read and prefer:

if (myObject != null)

I've found some articles and stack overflow questions discussing the merits of ReferenceEquals with respect to operator overloading, but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
483 views
Welcome To Ask or Share your Answers For Others

1 Answer

but outside of the operator overloading scenario, is there any benefit to ReferenceEquals vs == ?

No - the only advantage (and I'd argue it's not much of an advantage) to explicitly using Object.ReferenceEquals would be that it will never use the overloaded operator equals. In the non-overloaded case, the == Operator is defined to "returns true if its two operands refer to the same object" for all "reference types other than string". As such, its equivalent (provided its not overloaded).

I, personally, also favor using the second syntax, and find it more maintainable for null checking. I'd also argue that any overloaded operator== should also provide proper checking against null, and in the case where it did not for some reason (which would be odd), there'd likely be a specific rationale behind that decision which would cause you to want to use the overload, not ReferenceEquals.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...