Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Difference between “==” and .Equals () Method:

Posted by Ravi Varma Thumati on May 5, 2009

When we do coding in .NET, we get confused with few methods like when to use “==” operator and when to use .Equals () method. Here we are going to discuss the best possible ways where we can use these two methods.  

 For Value Type:

 In value type both “==” 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));

 Output:

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));

Output:

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 Type use “==” operator and use “Equals ()” method while performing value comparison with Reference Type

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: