473,738 Members | 2,645 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

== versus .Equals()

This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?

I see a lot of code that performs object evaluation e.g. Is Object1 the
same as Object2 by using == which works but shouldn't it be using
.Equals()? e.g. Object1.Equals( Object2)

I believe == should be using for simple type evaluation e.g.

int a = 0;
a++;

if (a == 1) {
... do something
}

Any opinions?

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
4 3211
Chris wrote:
This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?

I see a lot of code that performs object evaluation e.g. Is Object1 the
same as Object2 by using == which works but shouldn't it be using
Equals()? e.g. Object1.Equals( Object2)

I believe == should be using for simple type evaluation e.g.

int a = 0;
a++;

if (a == 1) {
... do something
}

Any opinions?


== is implemented as an operator which is a static method call. In your
case, Object1.Equals( Object2) you're depending on Object1 being a live
object, if it's null you're getting an exception.

Here's the rules I use:

- for all built-in types, use == for value comparison,
Object.Referenc eEquals for reference comparison
- for all other types, I check if they have a == operator and use that
if they do, otherwise I use .Equals but then I also make sure to check
against null

--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
mailto:la***@vk arlsen.no
PGP KeyID: 0x0270466B
Nov 16 '05 #2
> This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?


The == operator uses the static method op_Equality while Equals is an
instance method inherited from Object. Since the methods are members of each
class, or inherited from a base class, the implementation will vary from
class to class. However, in most scenarios you should get the same result if
whether you use the == operator or the Equals method.
To explain the differences I will use the String class as an example.
The String class inherits the instance method Equals from System.Object, has
an overloaded == operator and has its own static Equals method. The String
class can have a static method with the same name as the instance method
Equals inherited from Object since the methods have different signatures.

When using the == operator, the String class uses the static Equals method
internally. This method first uses the == operator to check if the strings
to compare are the same object. This is equal to using the
Object.Referenc eEquals mehtod.
If neither of the strings to compare are null, the static Equals method
calls the instance method Eqauls on the string to the left of the operator
and passes the string to the right of the operator as a parameter to perform
a string compare.
The C# compiler ensures that all strings with the same content all point to
the same object. Both s1, s2 and s3 in the following example point to the
same physical string object in memory, and hence have reference equality.
string s1="abc";
string s2="abc";
string s2=new string(new char[] {'a','b','c'});

When string comparsions the == operator is slower than the Equals method
when the strings are the same. If the strings are different the Equals
method will be faster. However, string comparison in .NET is super fast, so
in a real world application this won't make a difference.

Using the Equals operator determines whether two Object instances are the
same. The == operator determines whether two Objects have the same value.
Keep in mind that user-defined types can overload the == operator and the
Equals method alter their behavior.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
Nov 16 '05 #3
"Chris" wrote:
This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?


The fundamental rule is to make sure the thing you choose does what you
want/expect. This usually involves reading the documentation ;-)

Everything has an Equals method (since it comes from Object).

For a reference type (class/array), the default behavior of Equals is
reference equality. Classes can override it to provide value equality if they
want to - the docs for a class should tell you the behavior.

For a value type (struct/enum), the default behavior of Equals is value
equality (pairwise comparison of all the fields using their Equals method).

Not everything has an == operator (all classes do but a struct may or may
not have one).

The default behavior of == on a class is the same as the default behavior of
the Equals method for a class; that is, reference equality. The class
designer can overload the operator to perform value equality if they would
like to. Check the docs to see the behavior.

structs do not get an == operator for free. If you try to use == and the
struct designer did not overload it, your code won't compile. Of course, the
type designer can overload the operator to do whatever they want.

So I think it comes down to reading the docs and personal preference.

Mark
Nov 16 '05 #4
Chris <no****@devdex. com> wrote:
This is something that has been bugging me for some time. When exactly
should I be using == instead of .Equals() ?


See http://www.pobox.com/~skeet/csharp/faq/#equals

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
8418
by: Axel Dahmen | last post by:
Hi, I always thought that "1em" equals one line height. But if I replace <br><hr><br> by <hr style="margin: 1em 0;">
53
4284
by: SK | last post by:
Hi I appreciate all of the feedback I have recieved. I am enjoying working on my program and I hope that it can be appreciated. I have my program compiling now and I am continuing to work out the bugs. I have two problems that I cannot seem to resolve: 1. I want to have someone enter in as many employees as they want to..and for each employee entered I would like to save the data from that entry to print out at the end of the...
4
2541
by: Kurt | last post by:
Wouldn't you agree all of the follwoing should produce the same result? r = (o1 == o2); r = (o2 == o1); r = object.Equals(o1, o2); r = object.Equals(o2, o1); r = (o1.Equals(o2)); r = (o2.Equals(o1));
18
4743
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
10
5258
by: Jim Carlock | last post by:
Looking for a way to extract the path from the pfqpn (partially full qualified path name). $sThisServer = $_SERVER; // returns either aquaticcreationsnc.com or www.aquaticcreationsnc.com $sThisServer = $_SERVER; // returns aquaticcreationsnc.com whether or not the end-user typed // in the preceding www.
4
3601
by: mitch | last post by:
Suppose I have a DOM element, say a td, and I want to add a value to it to be used later. I am unclear on when it's OK to do td.myAttr = "hello"; versus when I need to do td.setAttribute("myAttr", "hello"); Could somebody explain the difference between these two?
10
105192
by: r035198x | last post by:
The Object class has five non final methods namely equals, hashCode, toString, clone, and finalize. These were designed to be overridden according to specific general contracts. Other classes that make use of these methods assume that the methods obey these contracts so it is necessary to ensure that if your classes override these methods, they do so correctly. In this article I'll take a look at the equals and hashCode methods. ...
7
2668
by: =?Utf-8?B?QWxleCBDb2hu?= | last post by:
In C++, there is an easy technique to provide an overloaded Equals() method. A straightforward translation to C# causes a stack overflow. Why does b.Equals(ba) in the snippet below not understand that it should call (ba as B).Equals(b) inside? Thanks in advance, Alex code sample follows:
1
1211
by: shapper | last post by:
Hello, What is the difference between using: from a in A join b in B on a.Name equals b.Name select a; and:
0
8787
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9334
jinu1996
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...
0
9208
tracyyun
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...
0
8208
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, 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...
1
6750
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4824
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
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
3
2193
bsmnconsultancy
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...

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.