Click here to Skip to main content
Full site     10M members (39.6K online)    

What is the 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.
So for example if you create an object as shown in below code:-
  1. “.NET interview questions” is the content.
  2. “o” is the 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.
 

You can also watch the following video of the above explanation at C# interview questions and answers :- Difference between "==" and ".Equals()" ?

 
You must Sign In to use this message board.
Search 
Per page   
GeneralMy vote of 3
John Brett
28 Apr '13 - 22:19 
The article really should have stressed that whilst strings are different from objects, they are only different because the string class overrides Equals, and this is a technique available to any class-writer.
I don't feel that the article really deals with this.
GeneralRe: My vote of 3
Shivprasad koirala
2 May '13 - 19:52 
Very good input under the hoods thats what happens.I will update the article with this note. Thanks for adding value.
My book .NET interview questions with 500 mostly asked questions in .NET world .NET Interview questions and answers

Generalsmth wrong
mythteria
26 Apr '13 - 21:32 
object o = ".NET Interview questions";
object o1 = new string(".NET Interview questions".ToCharArray());
Console.WriteLine(o == o1); //false
oops. a good explanation can be found here.
http://stackoverflow.com/a/3678810[^]
GeneralRe: smth wrong
Shivprasad koirala
26 Apr '13 - 21:54 
???? yes it is false....did i say anything different.
 
Skeet is Skeet...So i am a very small person to contradict him even in dreams.
My book .NET interview questions with 500 mostly asked questions in .NET world .NET Interview questions and answers


Last Updated 27 Apr 2013 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2013