Friday, July 13, 2007

Difference between == and .Equals Method?

What is Difference between == and .Equals() Method?

I have blogged on this topic before, but was not fully satisfied and so explaining the difference in more better way.

For Value Type: == and .Equals() method usually compare two objects by value.

For Example:

int x = 10;

int y = 10;

Console.WriteLine( x == y);

Console.WriteLine(x.Equals(y));

Will display:

True

True


For Reference Type: == performs an identity comparison, i.e. it will only return true if both references point to the same object. While Equals() method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:

StringBuilder s1 = new StringBuilder(“Yes”);

StringBuilder s2 = new StringBuilder(“Yes”);

Console.WriteLine(s1 == s2);

Console.WriteLine(s1.Equals(s2));

Will display:

False

True

In above example, s1 and s2 are different objects hence “==” returns false, but they are equivalent hence “Equals()” method returns true. Remember there is an exception of this rule, i.e. when you use “==” operator with string class it compares value rather than identity.

When to use “==” operator and when to use “.Equals()” method?

For value comparison, with Value Tyep use “==” operator and use “Equals()” method while performing value comparison with Reference Type.

4 comments:

deepak aggarwal said...

If Equals for reference type evaluate objects, then
int[] arr1 = { 1 };
int[] arr2 = { 1 };
Console.WriteLine((arr1 == arr2) + “::” + (arr1.Equals(arr2)) + “::” + (ReferenceEquals(arr1, arr2)));

returns false. First and third condition return false is faitr. But why does equals also return false as they are equivalent objects. Infact is stringbuilder the only exception between == and equals, or there is some other example also?

Deepa Hoysala said...

As it is mentioned you can use it for all reference types like objects.
ex:
object obj1 = new object();
object obj2 = new object();
Console.WriteLine(obj1 == obj2);

DotNetGuts said...

Guidelines for using == and .Equal Operator in .Net

Guidelines for == and .Equal Operator

Palanivel said...

Can you explain exact difference between == and .Equals() method?

Is it correct the following points?
1. == is operator while .Equals is method.
2. == is used to the value comparison
while .Equals methods is used to compare values with reference type.

Most Recent Post

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape