Link to home
Start Free TrialLog in
Avatar of Mr_Fulano
Mr_FulanoFlag for United States of America

asked on

Class Methods - "Equals" and "ReferenceEquals"

Hi, I'm using MS VS2010, C#.NET. I have what may be somewhat of an academic question.

I created a custom Class in one of my applications. As a default, the Class has two methods in it. Those being the "Equals" and "ReferenceEquals" methods.

Why is this a default? I would assume that my custom Class is getting the methods through inheritance from perhaps the Object Class, but why would any Class want to have such methods as defaults?

Thanks for your help,
Fulano
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I just give you an example about strings.

String is a class, you know.

We declare

string s1 = "hello";
string s2 = "hello";

If you call Equals method - they are equal! (Just because that the Equals is overridden for strings).
And, obviously, references are not same - these are two different objects.

In most cases Equals and ReferenceEquals return the same result. But not for strings and some other objects.

And, of course, you may override the behaviour for your custom class.
@anarki_jimbel

Your example is flawed because string literals are interned. In your example, those two string actually are the same references!

e.g.

Console.WriteLine(object.ReferenceEquals(s1, s2));

Open in new window

An example of where the two strings would not be the same reference:

string s1 = typeof(string).Name;
string s2 = "String";

Console.WriteLine(string.Equals(s1, s2));
Console.WriteLine(string.ReferenceEquals(s1, s2));

Open in new window

Agreed, you are right.
Avatar of Mr_Fulano

ASKER

Gentlemen, thank you both....and very nicely stated! Very good analysis Kaufmed. Your explanation is very well stated and well supported with your examples. Thank you for sharing and helping me understand that...it was puzzling me as to why I would want those methods, but you actually helped me see deeper into the theory of the code.

Good job!

Fulano
Excellent explanation!
NP. Glad to help  = )