Mr_Fulano
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
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
@anarki_jimbel
Your example is flawed because string literals are interned. In your example, those two string actually are the same references!
e.g.
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));
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));
Agreed, you are right.
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
Good job!
Fulano
ASKER
Excellent explanation!
NP. Glad to help = )
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.