Equality vs Sameness

G

Gary Brown

Hi,

In C#, how do you determine two objects are the "same" rather
than "equal?" In C/C++ you can check the addresses and LISP
provides a rich set of equality operators but C# appears ambiguous.

Search of the on-line documentation of "equal" and "same" yielded
nothing useful.

Thanks,
Gary
 
B

Bruce Wood

There is no hard-and-fast rule in C#, but the convention is (for
reference types) that == compares for "sameness," while .Equals()
compares for equality.

However, in C# as in C++, you can overload == and break that
convention. (And, yes, it's considered bad form.)
 
G

Guest

Let me add one more piece to the Equals puzzle. By default, Object.Equals()
tests referential equality and, therefore, does the same thing as
ReferenceEquals. The difference is that Equals is a virtual method and can,
and IMO usually should, be overridden in your object class.

The == operator, on the other hand, can but should not be overridden in any
reference types. It is acceptable to override the == operator in value types.

Like Peter says, ReferenceEquals is the sure way because it is not virtual.

So, in addition to the static ReferenceEquals, you can use both the static
and the instance versions of Equals if you have not overridden Equals in your
class.

Hopefully all this doesn't confuse you but it is all part of the bigger
picture of reference equality.
 
J

Jon Skeet [C# MVP]

Dale said:
Let me add one more piece to the Equals puzzle. By default, Object.Equals()
tests referential equality and, therefore, does the same thing as
ReferenceEquals. The difference is that Equals is a virtual method and can,
and IMO usually should, be overridden in your object class.

Usually should? Very few of the classes I write will ever be checked
for equality. The "You Ain't Gonna Need It" principle of agile
development suggests that it's not worth overriding Equals until you
actually need it to be overridden - which has saved me a lot of code...

(That's especially true as you should override GetHashCode when you
override Equals...)
The == operator, on the other hand, can but should not be overridden in any
reference types. It is acceptable to override the == operator in value types.

So do you believe that == shouldn't have been overloaded (not
overridden - you can't override operators) for System.String?

For immutable reference types which are effectively acting as "value
objects", I see nothing wrong with overloading ==. It can make code a
lot more readable.
 
G

Guest

Good call on my misuse of overriding vs overloading.

And I agree about overloading == for strings. The MS guidelines for
overloading operators do suggest overloading == for strings and other
reference types that act like value types. So maybe "any" was too strong of
a word. But between you and me, I can't think of a reason to overload == for
a string. I guess it just hasn't come up in my experience.

So, *grin*. let's heat things up and get to the last item... Overriding
Equals and GetHashCode.

I agree about not writing code that hasn't been asked for. Developers
shouldn't add operations to a class because they think the user would benefit
from it in the future if the users haven't asked for that functionality. But
while that applies to business logic, there are basic functionality expected
in objects that I always include.

For instance, I never create a CollectionBase based class and leave out
IndexOf or Contains just because when I create the class I don't know if it
will be used. It is a collection and all developers on the team will expect
the collections I create to have that functionality without having to put in
a change request to get it.

I am the same way about Equals. If you have a custom collection for your
class, IndexOf, Contains, and many other methods require value equality, not
referential equality, in order to work. If your class implements IComparable
so you can sort it, you have to override Equals as well.

It's just my opinion but, to me, overriding Equals is a good practice and
time well spent in any class except the most trivial or those with very
specific functional limitations that would make them exceptions


--
Dale Preston
MCAD C#
MCSE, MCDBA
 
J

Jon Skeet [C# MVP]

Dale said:
Good call on my misuse of overriding vs overloading.

And I agree about overloading == for strings. The MS guidelines for
overloading operators do suggest overloading == for strings and other
reference types that act like value types. So maybe "any" was too strong of
a word. But between you and me, I can't think of a reason to overload == for
a string. I guess it just hasn't come up in my experience.

So you find:

if ((x==null && y==null) || (x != null && x.Equals(y)))
or
if (object.Equals(x, y))

as easy to read as

if (x==y)

?

That's the only real reason - readability. Personally, I think that's a
really big, good reason.
So, *grin*. let's heat things up and get to the last item... Overriding
Equals and GetHashCode.

I agree about not writing code that hasn't been asked for. Developers
shouldn't add operations to a class because they think the user would benefit
from it in the future if the users haven't asked for that functionality. But
while that applies to business logic, there are basic functionality expected
in objects that I always include.

Always? So you override Equals and GetHashCode even for forms, web
pages, singletons etc? How often have you seen a Form used as the key
in a hashtable, or wanted to compare two instances of a singleton?

Just looking through my miscellaneous utility library... how often
would you want to compare instances of threadpools other than by
reference? Hash-creators? Binary diff decoders? Bit converters? Binary
readers? The only thing in my library where it makes sense to compare
instances is Utf32String, which of course *does* override Equals and
GetHashCode (and overloads ==).
For instance, I never create a CollectionBase based class and leave out
IndexOf or Contains just because when I create the class I don't know if it
will be used. It is a collection and all developers on the team will expect
the collections I create to have that functionality without having to put in
a change request to get it.

They could easily create the functionality if it's needed though.
(Personally I never create CollectionBase based classes anyway...)
I am the same way about Equals. If you have a custom collection for your
class, IndexOf, Contains, and many other methods require value equality, not
referential equality, in order to work. If your class implements IComparable
so you can sort it, you have to override Equals as well.

And that's fine for classes where it makes sense to compare instances -
but in a lot of cases it doesn't. I'd say that fewer than half of my
objects make sense to compare with other instances - that's a lot of
work to do for the other half just for the sake of consistency.

Using dependency injection, these days for many of my classes only a
single instance will ever be created. There's nothing to *stop* new
instances being created, but they just won't tend to be. Why would I go
to the hassle of overriding Equals and GetHashCode for those classes?
It's just my opinion but, to me, overriding Equals is a good practice and
time well spent in any class except the most trivial or those with very
specific functional limitations that would make them exceptions

To override them you have to:

1) Write unit tests for all the different possibilities (checking null,
checking that each appropriate field is used in the equality, etc)

2) Write the implementation

3) Keep the tests and implementation up to date

Point 3 is the biggest, in a way - how sure are you that if you add a
field later on, you *always* remember to update Equals and GetHashCode?
If you don't, you end up with a class which provides a sort of version
of the functionality desired (if it *is* actually desired).

Do you think MS should have overridden Equals for FileStream? If so,
what should it have done? How about Thread?

It's not unreasonable to override Equals and GetHashCode for types
which will reasonably compared for value equality - but that's *far*
from all of even most types, IME.

Even where it would *potentially* be useful, I wouldn't usually bother
until it's needed - but it depends how much bureaucracy is required in
order to change something later. In my situation, when someone needed
equality, they could implement it themselves with little more effort
(if any) than if I'd done it in the first place. Embrace change :)
 
G

Guest

Well, I do admit you have come up with a lot of types for which overriding
Equals would not offer any benefit. So for those types of functional
classes, I agree with you. I'll have to be more careful about my
generalizations in the future.

--
Dale Preston
MCAD C#
MCSE, MCDBA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top