Difference Between the == Operator and .Equals method

Introduction

 
In this blog, we are discussing the difference between the == Operator and the .Equals method. Let's discuss it with a simple program.
 
When we create the object, we have two parts: one is the content of the object and the other one is the reference to that contact.
As an example, please see the below code.  Hello C# Corner will be the content and obj will be the reference to the content.  
  1. object obj = "Hello C# Corner";// Hello C# Corner becomes content  
  2. object obj2 = obj;// obj becomes reference to that content.  
I have created a simple object obj, and in the next line, I am creating one more object, obj2, and passing obj as a reference.
What will happen internally is basically both obj and obj2 point towards the same reference and will also have the same content. If we do an equal to equal comparison or an equals method comparison for both of them, it should give the same result since both object contents are the same. 
 
Please check the below code and the result.
  1. Console.WriteLine(obj == obj2);  
  2. Console.WriteLine(obj.Equals(obj2));  
  3. Console.ReadLine();  
Result of the program is:
 
 
 
Let's go ahead and change the code In the below code, I am a fresh object and pass it to obj1.
  1. object obj = "Hello C# Corner";// obj becomes content  
  2. object obj2 = new string("Hello C# Corner".ToCharArray());  
  3. Console.WriteLine(obj == obj2);  
  4. Console.WriteLine(obj.Equals(obj2));  
  5. Console.ReadLine();  
 
In this case, the object obj pointing towards the Hello C# Corner content and one more object is pointing towards the same content but it is a fresh object. In this case, when we use equal to equal to comparison should return the false and equals method will return the true result. why because the content is the same but object references are different. 
 
Result of the above program is:
 
 
 
KeyPoints to Remember
  1. The "==" operator helps to compare object reference. 
  2. ".Equals" method helps to compare content.
  3. If you are using data type always does a content comparison.
 
Summary 
 
In this blog, we are discussed about the difference between the == Operator and .Equals method.