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.

 

 

 

 

 

 

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s