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 7 1975
object.Referenc eEquals().
"Gary Brown" <ga********@cha rter.net> wrote in message
news:%2******** ********@TK2MSF TNGP09.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
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.)
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
Dale <da******@nospa m.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.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
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******@nospa m.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.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet If replying to the group, please do not mail me too
Dale <da******@nospa m.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.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
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******@nospa m.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.co m> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet If replying to the group, please do not mail me too This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 );
}
|
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 object.
So if we have
const char * foo = "foo" , * bar = "bar" ;
int foobar = ( foo == bar ) ;
would it mean that foobar is undefined?
|
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 objects of class A, ComboBox2
contains objects of class B). What I'm trying to do is determine if a given
object is contained in one of the comboboxes, i.e.:
Combobox1.Items.Contains(MyA);
Combobox2.Items.Contains(MyB);
Now the problem is...
|
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 recursivelly until the comparison of value type is reached. I
found in Reflections only getting of public members. Although the internal
state of an object should not be interesting for evalution of equality I
would like to make a value equality check also...
|
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 resulted in no hits
I also searched for: XML equality schema (single words) on the same
newsgroups gave very little and not-to-the-point links
| |
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 behaviour, which is
returning a value which is, really, id({}) < id().
He also said that default equality comparison will continue to be
identity-based. This means that x == y will never raise an exception,
as is the situation is now. Here's his reason:
|
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 based on the position of the point in the vector rather than
its x,y or any other criterion. Thus 2 free point (which are not in
the vector are always unequal ) and so on.
How to add this kind of equality operator ? Is comparing memory
location like...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
| |
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |