473,386 Members | 1,819 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,386 software developers and data experts.

== 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 3186
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.ReferenceEquals 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***@vkarlsen.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.ReferenceEquals 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.com>
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
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
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...
4
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 =...
18
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...
10
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 ...
4
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 ...
10
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...
7
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...
1
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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:
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
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...

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.