473,396 Members | 1,859 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 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 1956
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

26
by: Alexander Block | last post by:
Hello newsgroup, let's say I have a function like template<class Type> inline bool areEqual(const Type &a, const Type &b) { return ( a == b ); }
40
by: Ike Naar | last post by:
In K&R "The C++ programming language (2nd ANSI C edition), the reference manual states (paragraphs 7.9 and 7.10) that pointer comparison is undefined for pointers that do not point to the same...
4
by: Matt Burland | last post by:
I'm a little confused about the way the default equality operator works with classes. Here's the situation, I have two comboboxes that are each filled with different object (i.e. ComboBox1 contains...
2
by: Marcel Sottnik | last post by:
Hallo NG Does anyone have an idea how could one implement, a general routine for value equality ? I mean something using Reflections to get all the members of a class and compare them...
6
by: onetitfemme | last post by:
Hi *, I have been looking for a definition or at least some workable concept of "XML equality". Searching on "XML equality" in comp.text.xml, microsoft.public.xsl and microsoft.public.xml...
37
by: spam.noam | last post by:
Hello, Guido has decided, in python-dev, that in Py3K the id-based order comparisons will be dropped. This means that, for example, "{} < " will raise a TypeError instead of the current...
3
by: toton | last post by:
Hi, I have a struct Point { int x, int y; } The points are stored in a std::vector<Pointpoints; (global vector) I want to add equality (operator == ) for the point, which will check equality...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.