Difference between “==” and .Equals()

When we create any object there are two parts to the object one is the content and the other is reference to that content.|

object o = “.NET Interview questions”;

 

“==” compares if the object references are same while “.Equals()” compares if the contents are same.

 

So if you run the below code both “==” and “.Equals()” returns true because content as well as references are same.

 

 

 

object o = “.NET Interview questions”;

object o1 = o; Console.WriteLine(o == o1);

Console.WriteLine(o.Equals(o1));

Console.ReadLine();

 

True

 

True

 
Now consider the below code where we have same content but they point towards different instances. So if you run the below code both “==”   will return false and “.Equals()”  will return true.

 

 

 

object o = “.NET Interview questions”;
object o1 = new string(“.NET Interview questions”.ToCharArray());
Console.WriteLine(o == o1);
Console.WriteLine(o.Equals(o1));
Console.ReadLine();

 

False

 

True

 
When you are using string data type it always does content comparison. In other words you either use “.Equals()” or “==” it always do content comparison.

 

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