Avatar of Mr_Fulano
Flag 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,
C#.NET Programming

Avatar of undefined
Last Comment

8/22/2022 - Mon

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Dmitry G

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.


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


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

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Dmitry G

Agreed, you are right.

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!


Excellent explanation!
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.

NP. Glad to help  = )