471,314 Members | 2,185 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,314 software developers and data experts.

Equality vs Sameness

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
Jan 30 '06 #1
7 1863
object.ReferenceEquals().

"Gary Brown" <ga********@charter.net> wrote in message
news:%2****************@TK2MSFTNGP09.phx.gbl...
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

Jan 30 '06 #2
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.)

Jan 30 '06 #3
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.
--
Dale Preston
MCAD C#
MCSE, MCDBA
"Gary Brown" wrote:
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

Jan 30 '06 #4
Dale <da******@nospam.nospam> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jan 31 '06 #5
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
"Jon Skeet [C# MVP]" wrote:
Dale <da******@nospam.nospam> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Feb 1 '06 #6
Dale <da******@nospam.nospam> wrote:
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 :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 1 '06 #7
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
"Jon Skeet [C# MVP]" wrote:
Dale <da******@nospam.nospam> wrote:
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 :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Feb 1 '06 #8

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

26 posts views Thread by Alexander Block | last post: by
40 posts views Thread by Ike Naar | last post: by
4 posts views Thread by Matt Burland | last post: by
2 posts views Thread by Marcel Sottnik | last post: by
6 posts views Thread by onetitfemme | last post: by
37 posts views Thread by spam.noam | last post: by
3 posts views Thread by toton | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.