Object Comparisons — Difference between Equals method and ==

When we compare two objects with same content,there is a difference between “Equals and  == “.

Equals :

The Equals method does the content based comparison between two objects.

== :

“==” compares only object references.

Scenarios :


Sample s = new Sample () { a = "Hey" };
Sample s1 = s;
Sample s4 = new Sample () { a = "Hey" };

 Console.WriteLine(s1==s);  // True --Compares the instances 

Console.WriteLine(s==s4); // False ---Eventhough content is same,still == looks only for reference.

Console.WriteLine(s.Equals(s4)); // True --- Compares the value in field "a"  in both object and returns true.

String is an exceptional case and its immutable. It behaves with == as Equals.